I wish to read incoming XML files that have no specific name (e.g. d开发者_开发技巧ate/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.
You need to provide the path to file too:
file = open(os.path.join(path,infile),'r')
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
).
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
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')
精彩评论