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:
import os
for path, subdirs, files in os.walk('\Users\user\Desktop\Test_Py'):
for filename in files:
f = os.path.join(path, filename)
a = open("output.txt", "w")
a.write(str(f))
This lists the names of the files in the folders (there are 6) but each new file overwrites the old so there is only one file name in the output.txt file at any given time. How do I change this code so that it writes all of the file names in the output.txt file?
Use the os. listdir('path') function to get the list of all files of a directory. This function returns the names of the files and directories present in the directory.
Right-click that folder and select Show more options. Click Copy File List to Clipboard on the classic menu. You'll still need to paste the copied list into a text file. Launch Run, type Notepad in the Open box, and click OK.
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
with open("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)
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")
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With