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.