Python: List all the file names in a directory and its subdirectories and then print the results in a txt file
Question: 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?


Answer: 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) 
    

