Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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?

like image 311
Adilicious Avatar asked Aug 30 '12 14:08

Adilicious


People also ask

How do I get a list of files in a directory in Python?

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.

How do I get a list of files in a folder from text?

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.


3 Answers

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) 
like image 129
gefei Avatar answered Sep 29 '22 14:09

gefei


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")
like image 39
Emmett Butler Avatar answered Sep 29 '22 12:09

Emmett Butler


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) 
like image 36
CRitesh Avatar answered Sep 29 '22 12:09

CRitesh