Search code examples
pythonpathloadfile-not-foundlistdir

Getting error: FileNotFoundError: [Errno 2] No such file or directory when using Python open()


I have seen many similar questions to mine, but still I can't resolve the issue. I'd be grateful if someone could help. I have a folder with 3 .txt files (Text1.txt, Text2.txt, & Text3.txt) in it, plus some other files. I want to read these three files and pass them through a function. I wrote a for loop as follows:

file_list = [f for f in listdir("Path_to_my_files") if 
isfile(join("Path_to_my_files",f))]

def Read (files):
    for f in files:
      if f.endswith (".txt"):
        data = open(r'Path_to_my_files/f')
        text = data.read()

The error message I get is: FileNotFoundError: [Errno 2] No such file or directory: 'Text1.txt'

What am I doing wrong?


Solution

  • You can use glob, i.e.:

    from glob import glob
    
    p = "/path/to/*.txt"
    for t in glob(p):
        with open(t) as f:
            text = f.read()
        # do something with text