1

I wish to read incoming XML files that have no specific name (e.g. date/time naming) to extract values and perform particular tasks. I can step through the files but am having trouble opening them and reading them.

What I have that works is:-

 import os
 path = 'directory/'
 listing = os.listdir(path)
 for infile in listing:
      print infile

But when I add the following to try and read the files it errors saying No such file or directory.

      file = open(infile,'r')

Thank you.

1
  • Excellent, thank you all for your answers and explaination, very helpful. Commented Sep 16, 2011 at 1:21

4 Answers 4

3

You need to provide the path to file too:

file = open(os.path.join(path,infile),'r')
Sign up to request clarification or add additional context in comments.

Comments

3

os.listdir provides the base names, not absolute paths. You'll need to do os.path.join(path, infile) instead of just infile (that may still be a relative path, which should be fine; if you needed an absolute path, you'd feed it through os.path.abspath).

Comments

3

As an alternative to joining the directory path and filename as in the other answers, you can use the glob module. This can also be handy when your directories might contain other (non-XML) files that you don't want to process:

import glob
for infile in glob.glob('directory/*.xml'):
    print infile

Comments

2

You have to join the directory path and filename, using

os.path.join(path, infile)

Also use the path without the / :

path = 'directory'

Something like this (Not optimized, just a small change in your code):

import os
 path = 'directory'
 listing = os.listdir(path)
 for infile in listing:
      print infile
      file_abs = os.path.join(path, infile)
      file = open(file_abs,'r')

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.