The general solution would be to:
- use the
os.walk()
function to traverse the directory tree. - Iterate over the filenames and use
fn_name.endswith('.cpp')
with if/elseif to determine which file you're working with - Use the
re
module to create a regular expression you can use to determine if a line contains your tag - Open the target file and a temporary file (use the
tempfile
module). Iterate over the source file line by line and output the filtered lines to your tempfile. - If any lines were replaced, use
os.unlink()
plusos.rename()
to replace your original file
It's a trivial excercise for a Python adept but for someone new to the language, it'll probably take a few hours to get working. You probably couldn't ask for a better task to get introduced to the language though. Good Luck!
----- Update -----
The files
attribute returned by os.walk is a list so you'll need to iterate over it as well. Also, the files
attribute will only contain the base name of the file. You'll need to use the root
value in conjunction with os.path.join()
to convert this to a full path name. Try doing just this:
for root, d, files in os.walk('.'):
for base_filename in files:
full_name = os.path.join(root, base_filename)
if full_name.endswith('.h'):
print full_name, 'is a header!'
elif full_name.endswith('.cpp'):
print full_name, 'is a C++ source file!'
If you're using Python 3, the print statements will need to be function calls but the general idea remains the same.