Reputation: 3
I have a loop supposed to iterate through a list of files
import os
for fil in os.listdir('dir/'):
with open(fil) as f:
for line in f:
#process line
My files contain text but they have weird extensions such as filea.234234 fileb.34234
When I run the script I get the error
IOError: [Errno 2] No such file or directory: 'filea.234234'
What is the cause of this error?
ps. The are way too many files to rename them if that is the cause
Upvotes: 0
Views: 65
Reputation: 23296
You can also use the glob
module:
import glob
import os
for filename in glob.glob(os.path.join('dir', '*')):
# etc...
In either case you might want to make sure the filename is not a directory before trying to open it, depending on whether or not you can be sure the directory only contains files.
Upvotes: 0
Reputation: 33046
Those files are located under dir/
, not in the working directory. You are trying to open ./filea.234234
, while you should be opening dir/filea.234234
. Fix your code accordingly:
import os
for fil in os.listdir('dir/'):
with open(os.path.join("dir", fil)) as f:
for line in f:
# ...
Upvotes: 4