Python: List All The File Names In A Directory And Its Subdirectories And Then Print The Results In A Txt File
My problem is as follows. I want to list all the file names in my directory and its subdirectories and have that output printed in a txt file. Now this is the code I have so far: i
Solution 1:
don't open a file in your for
loop. open it before your for
loop
like this
import os
a = open("output.txt", "w")
for path, subdirs, files in os.walk(r'C:\Users\user\Desktop\Test_Py'):
for filename in files:
f = os.path.join(path, filename)
a.write(str(f) + os.linesep)
Or using a context manager (which is better practice):
import os
withopen("output.txt", "w") as a:
for path, subdirs, files in os.walk(r'C:\Users\user\Desktop\Test_Py'):
for filename in files:
f = os.path.join(path, filename)
a.write(str(f) + os.linesep)
Solution 2:
You are opening the file in write mode. You need append mode. See the manual for details.
change
a = open("output.txt", "w")
to
a = open("output.txt", "a")
Solution 3:
You can use below code to write only File name from a folder.
import os
a = open("output.txt", "w")
for path, subdirs, files in os.walk(r'C:\temp'):
for filename in files:
a.write(filename + os.linesep)
Post a Comment for "Python: List All The File Names In A Directory And Its Subdirectories And Then Print The Results In A Txt File"