Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

ioerror - Can't Open files from a directory in python

I have written a small module that first finds all the files in the directory, and merge them. But, I'm having the problem with opening these files from a directory. I made sure that my files and directory names are correct, and files are actually in the directory.

Below is the code..

 seqdir = "results"
 outfile = "test.txt"

 for filename in os.listdir(seqdir):
     in_file = open(filename,'r') 

Below is the error..

     in_file = open(filename,'r')     
     IOError: [Errno 2] No such file or directory: 'hen1-1-rep1.txt'
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

listdir returns just the file names: https://docs.python.org/2/library/os.html#os.listdir You need the fullpath to open the file. Also check to make sure it is a file before you open it. Sample code below.

for filename  in os.listdir(seqdir):
    fullPath = os.path.join(seqdir, filename)
    if os.path.isfile(fullPath):
        in_file = open(fullPath,'r')
        #do you other stuff

However for files it is better to open using the with keyword. It handles closing for you even when there are exceptions. See https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects for details and an example


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...