Search code examples
pythonarraysstringreadfilelistdir

How to read all .txt files from a directory


I would like to read all the contents from all the text files in a directory. I have 4 text files in the "path" directory, and my codes are;

for filename in os.listdir(path):
    filepath = os.path.join(path, filename)
    with open(filepath, mode='r') as f:
        content = f.read()
        thelist = content.splitlines()
        f.close()
        print(filepath)
        print(content)
        print()

When I run the codes, I can only read the contents from only one text file.

I will be thankful that there are any advice or suggestions from you or that you know any other informative inquiries for this question in stackoverflow.


Solution

  • If you need to filter the files' name per suffix, i.e. file extension, you can either use the string method endswith or the glob module of the standard library https://docs.python.org/3/library/glob.html Here an example of code which save each file content as a string in a list.

    import os
    
    path = '.' # or your path
    
    files_content = []
    
    for filename in filter(lambda p: p.endswith("txt"), os.listdir(path)):
        filepath = os.path.join(path, filename)
        with open(filepath, mode='r') as f:
            files_content += [f.read()]
    
    

    With the glob way here an example

    import glob
    
    for filename in glob.glob('*txt'):
        print(filename)