Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loop through folder in python and open files throws an error

Tags:

python

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:
        ........
like image 418
Moe Siddig Avatar asked Mar 08 '17 22:03

Moe Siddig


People also ask

How do I iterate through file contents with open and open?

Use a for-loop to iterate through the lines of a file In a with-statement, use open(file, mode) with mode as "r" to open file for reading. Inside the with-statement, use a for-loop to iterate through the lines. Then, call str. strip() to strip the end-line break from each line.


1 Answers

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()
like image 198
mdh Avatar answered Oct 30 '22 12:10

mdh