I have a folder with 40 files in it which I want to loop through. When I print out the name of the file my code works fine:

import os
source = 'pathtofile'
for root, dirs, filenames in os.walk(source):
    for file in filenames:
        print file

It will print :


But if I try to open the file / files in the loop I get the following error. IO error: IOError: [Errno 2] No such file or directory: 'file.txt'

This is the code I am having issues with :

import os
import re

destdir = 'pathtofile'
files = [ f for f in os.listdir(destdir) if 
os.path.isfile(os.path.join(destdir,f)) ]

for f in files:
    with open(f, 'r') as var1:
        for line in var1: 
            if re.match('(.*)exception(.*)', line):
                print line

I have verified , and the string I am searching for, it does exist in the files.

Can you please provide some insight as to what is wrong with my code ? Thanks.

2 Months
Discussion Span
Last Post by Eric_8

I think you get this error because of with open(f, 'r') as var1. It should be
with open(os.path.join(destdir, f), 'r') as var1.

A more up-to-date approach is to use module pathlib

from pathlib import Path
destdir = Path('pathtofile')
files = [p for p in destdir.iterdir() if p.is_file()]
for p in files:
    with p.open() as f:

Edited by Gribouillis


@Gribouillis , Thank you very much for your answer. Now it is working !!!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.