21

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?

typ1232
  • 5,395
  • 6
  • 34
  • 50
Adilicious
  • 1,473
  • 3
  • 16
  • 21

4 Answers4

36

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) 
brian buck
  • 3,114
  • 3
  • 22
  • 24
gefei
  • 18,124
  • 7
  • 49
  • 65
7

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")
Mike Mackintosh
  • 13,530
  • 6
  • 58
  • 85
Emmett Butler
  • 5,469
  • 2
  • 28
  • 46
2

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) 
CRitesh
  • 21
  • 1
0

If you want to avoid creating new lines in the text file include newline='' within the context manager. You won't have to format your text file later.

Code to write names of all files in a folder/directory:

file_path = 'path_containing_files'
with open("Filenames.txt", mode='w', newline='') as fp:
    for file in os.listdir(file_path):
        f = os.path.join(file_path, file)
        fp.write(str(f) + os.linesep)

If you want to write the file names of a particular file type eg. XML, you can add an if condition:

file_path = 'path_containing_files'
with open("Filenames.txt", mode='w', newline='') as fp:
    for file in os.listdir(file_path):
        if file.endswith('.xml'):
            f = os.path.join(file_path, file)
            fp.write(str(f) + os.linesep) 
Jeru Luke
  • 16,909
  • 11
  • 66
  • 79