Can't Open files from a directory in python

前端 未结 1 1308
天命终不由人
天命终不由人 2020-12-18 15:17

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

相关标签:
1条回答
  • 2020-12-18 15:45

    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

    0 讨论(0)
提交回复
热议问题