12

I try to loop through folder and read files but only the first file will open and read correctly but the second files print the name and through an error "IOError: [Errno 2] No such file or directory:". I have tried the following

for filename in os.listdir("pathtodir\DataFiles"):
    if filename.endswith(".log"): 
        print(os.path.join("./DataFiles", filename))

        with open(filename) as openfile:    
        for line in openfile:
        ........
1
  • The file is not in ./DataFiles, according to the line of code that retrieves the list from pathtodir\DataFiles. You should first figure out where you're looking for the files at, settle on a forward or backslash (but not both), and then be consistent when you use that pathname. You have to open the file in the same folder you got it's name from; your code does not do that, because it tries to open filename without a path. The code you're using tries to access the same file in three separate locations, and it's only in one of them. Commented Mar 8, 2017 at 22:58

2 Answers 2

26

os.listdir() gives you only the filename, but not the path to the file:

import os

for filename in os.listdir('path/to/dir'):
    if filename.endswith('.log'):
        with open(os.path.join('path/to/dir', filename)) as f:
            content = f.read()

Alternatively, you could use the glob module. The glob.glob() function allows you to filter files using a pattern:

import os
import glob

for filepath in glob.glob(os.path.join('path/to/dir', '*.log')):
    with open(filepath) as f:
        content = f.read()
Sign up to request clarification or add additional context in comments.

Comments

2

Using os.listdir(...) only returns the filenames of the directory you passed, but not the full path to the files. You need to include the relative directory path as well when opening the file.

basepath = "pathtodir/DataFiles/"
for filename in os.listdir(basepath):
    if filename.endswith(".log"): 
        print(os.path.join("./DataFiles", filename))

        with open(basepath + filename) as openfile:    
            for line in openfile:
            ........

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.