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 :

File1
File2
...
File4

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.

Just a thought.

Line 5 calls out the directory but line 9 does not.

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:
        ...

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.