Can’t Open files from a directory in python [duplicate]

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

Leave a Comment