简体   繁体   中英

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'

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM