2

There is a list of document saved in a folder, I need to save the file name along with its path in a plain text file, such as

/document/file1.txt
/document/file2.txt
...

My question is how to iterate through a file folder and extract the path information for each file. Thanks.

user785099
  • 5,323
  • 10
  • 44
  • 62

1 Answers1

2

you can try something like this.

import os
output_file = open(filename, 'w')
for root, dirs, files in os.walk(".", topdown=False):
    for name in files:
        f = print(os.path.join(root, name))
        output_file.write(f)
    for name in dirs:
        print(os.path.join(root, name))
output_file.close()

you can also use listdir() method

file = open(filename, 'w')
    for f in os.listdir(dirName):
        f = os.path.join(dirName, f)
        file.write(f)
 file.close()
Rachit Tayal
  • 1,190
  • 14
  • 20