Search code examples
pythonioerror

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'

Solution

  • 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