Reputation: 347
I need to open the root folder named: 'data' and then to go get the list of folders in that folder and later to take the path of each and to execute some code that checks if inside those folders is a 'docx' file.
If a execute only this:
rootDir = 'data'
for dirName, subdirList, fileList in os.walk(rootDir):
if dirName == 'data':
pass
else:
print('Found directory: %s' % dirName)
As result I get a list of all folders
Found directory: data/2014 09 Daily Reports
Found directory: data/2014 11 Daily Reports
Found directory: data/2014 03 Daily Reports
Found directory: data/2015 04 Daily Reports
Found directory: data/2015 03 Daily Reports
Found directory: data/2015 08 Daily Reports
Found directory: data/2014 10 Daily Reports
Found directory: data/2015 07 Daily Reports
.....
But if I include this:
rootDir = 'data'
for dirName, subdirList, fileList in os.walk(rootDir):
if dirName == 'data':
pass
else:
dirpath = os.path.abspath(dirName)
for root, dirs, filenames in os.walk(dirpath):
for f in filenames:
os.chdir(dirpath)
fn = f.replace('\xc3\xab','e')
os.rename(f, f.replace('\xc3\xab','e'))
if 'docx' in f:
print 'docx files are found inside this folder'
else:
pass
print('Found directory: %s' % dirName)
if a execute this,the result is only this:
Found directory: data/2014 09 Daily Reports
Why is the for loop not executing? Any help?
Upvotes: 0
Views: 115
Reputation: 567
that's happening because you're executing os.chdir
inside the loop.
the os.walk
won't find the "data" directory inside the directory that it was changed to in the previous execution of the loop, you need either change rootDir
to provide the "full/path/to/data" directory or try to execute os.chdir("..")
inside the loop to go back the previous directory.
Upvotes: 2