1

I'm trying to let Python return all the file names (all .txt files) in subfolders. So I tried os.walk().

It worked okay for returning all the subfolder names:

path=r'C:\test\2017\QTR1'
fileNames = next(os.walk(path))[1]
print("Files = ",fileNames)

It returned: Files = ['1029199', '1078099', '1104188', '1120193', '1130713', '1141391', '1141688', '1303942', '1304741', '1326380', '1326801', '1328670', '1355839', '1365135', '1366246', '1380393', '1412665', '1433195', '1439404', '1466026', '1469134', '1470205', '1485074', '1503579', '1521951', '1598014', '1633917', '1653653', '20212', '357301', '36104', '36146', '4962', '51143', '718877', '763563', '906465', '927628', '93751', '94344'] ​ But when I tried to return all the file names, it only gave me an empty result:

path=r'C:\test\2017\QTR1'
fileNames = next(os.walk(path))[2]
print("Files = ",fileNames)

Does there have any errors with my 2nd part coding? Or do there have any better methods to read all subfolders' content? Thank you in advance

Ciercy
  • 51
  • 5

2 Answers2

1

os.walk() returns a generator which you need to consume. Each iteration produces a 3-tuple. It is documented here

Try this:

from os import walk
from fnmatch import filter
from os.path import join

PATH = r'C:\test\2017\QTR1'

filenames = []

for root, _, files in walk(PATH):
    filenames.extend([join(root, file) for file in filter(files, '*.txt')])

print(*filenames, sep='\n')
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
0
file_names = []

for folder_path, _, files in os.walk(path):
    for file in files:
        if file.endswith('.txt'):
            file_names.append(os.path.join(folder_path, file))
Kayvan Shah
  • 375
  • 2
  • 11