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())
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.