How to read folder file contents into a text file with Python

How to read folder file contents into a text file with Python - Do you need to take all existing files in a folder and read them into a text file? You are one method away from it. In this post we are going to use the listdir method from the os module to read all files in a folder. The listdir method returns a list containing the names of the entries in the directory given by path.

First, we import listdir from the os module. We then import the isfile and join from os.path. isfile checks that the file is really a file. the join method is used for especially joining os paths intelligently to avoid errors relating to file not found errors. The method getcwd returns the current working directory. Change this to your path if you do not want to run the script from the same folder all the time.

The last thing that we do is a list comprehension for the files. We read every file (f) for every file (f) in the current working directory returned by listdir (listdir(getcwd)). We only add f to the list if f is a regular file (if isfile(join(getcwd(), f))). We then create the file by reading each line in the onlyfiles list into the .txt file "output_files.txt".

from os import listdir
from os.path import isfile, join
from os import getcwd
onlyfiles = [f for f in listdir(getcwd()) if isfile(join(getcwd(), f))]

with open("output_files.txt", "w") as f:
    for line in onlyfiles:

Happy coding!

Featured image from Pixabay, link

Leave a Reply

Your email address will not be published. Required fields are marked *

linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram