无法从python中的目录打开文件

par*_*tel 4 python ioerror

我写了一个小模块,它首先找到目录中的所有文件,然后合并它们。但是,我在从目录中打开这些文件时遇到了问题。我确保我的文件和目录名称是正确的,并且文件实际上在目录中。

下面是代码..

 seqdir = "results"
 outfile = "test.txt"

 for filename in os.listdir(seqdir):
     in_file = open(filename,'r') 
Run Code Online (Sandbox Code Playgroud)

下面是错误..

     in_file = open(filename,'r')     
     IOError: [Errno 2] No such file or directory: 'hen1-1-rep1.txt'
Run Code Online (Sandbox Code Playgroud)

use*_*927 5

listdir 仅返回文件名:https://docs.python.org/2/library/os.html#os.listdir您需要完整路径才能打开文件。在打开它之前还要检查以确保它是一个文件。下面的示例代码。

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
Run Code Online (Sandbox Code Playgroud)

但是对于文件,最好使用with关键字打开。即使有异常,它也会为您处理关闭。有关详细信息和示例,请参阅https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects