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'

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x