Gabe H. Coud
Gabe H. Coud

Reputation: 175

Unabe to loop over files with Python

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

File 3

.....

File 40

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.

Upvotes: 0

Views: 111

Answers (1)

Gerges
Gerges

Reputation: 6499

This is what you want:

from os.path import join, isfile

files = [join(destdir, x) for x in os.listdir(destdir) if isfile(join(destdir, x))]

or if you know all files have .txt extension, you can do:

from glob import glob

files = glob(join(destdir, '*.txt'))

Upvotes: 1

Related Questions