Iterating through directories with Python
I need to iterate through the subdirectories of a given directory and search for files. If I get a file I have to open it and change the content and replace it with my own lines.
I tried this:
import os rootdir ='C:/Users/sid/Desktop/test' for subdir, dirs, files in os.walk(rootdir): for file in files: f=open(file,'r') lines=f.readlines() f.close() f=open(file,'w') for line in lines: newline = "No you are not" f.write(newline) f.close()
but I am getting an error. What am I doing wrong?
The actual walk through the directories works as you have coded it. If you replace the contents of the inner loop with a simple
import os rootdir = 'C:/Users/sid/Desktop/test' for subdir, dirs, files in os.walk(rootdir): for file in files: print os.path.join(subdir, file)
If you still get errors when running the above, please provide the error message.