Hi

I am not a very experienced programmer, but I searched around and couldn't fint an answer to my question, so I am posting it here.

I am trying to seach through a local directory and process all the files in that folder. The files are alle named "label" + " " + file_number. Processing the files is no problem, however I seem to get some rather strange errors when trying to read the files. The code i have been using to read the files is:

import os,glob

path = "C:\folder"

for subdir, dirs, files in os.walk(path):
    for file in files:
        f = open(file, 'r')
        print f.readlines()
        f.close()

Using this I am able to read file #0, however when it tries to read file #1 I get the following error:

IOError: [Errno 2] No such file or directory: 'label 1.dxp'

Could also mention that I am able to read file #10 by using a different approach (every other file gives errno 2, also #20 and #30), so could be a link there.

Thanks for your help.

os.walk returns the filenames without the path prefix. That is, you are trying to open them in the current directory, where they do not exist. change line 7 to

f = open(os.path.join(subdir, file), 'r')

PS: your variable names are misleading.

In single directory not descending in sub dirs:

import os
start = 'label'
for fn in (f for f in os.listdir(os.curdir) if f.startswith(start) and os.path.isfile(f)):
    print(fn)

Thank you very much, that did the trick! Will also try to pay more attention to my variable names :)

Just added tips ;)

import os
start = 'label'
for fn in (f for f in os.listdir(os.curdir) if f.startswith(start) and os.path.isfile(f)):
with open(fn) as fnFile:
  print(fnFile.read())

Edited 5 Years Ago by richieking: n/a

This question has already been answered. Start a new discussion instead.