无法从python目录打开文件

无法从python目录打开文件

问题描述:

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

下面是代码..

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

for filename in os.listdir(seqdir): 
    in_file = open(filename,'r') 

下面是错误..

 in_file = open(filename,'r')  
    IOError: [Errno 2] No such file or directory: 'hen1-1-rep1.txt' 
+0

问题可能是您没有使用绝对路径 - 请参阅isedev的刚发布的答案:) – 2014-09-26 17:25:18

listdir同时返回刚才的文件名:https://docs.python.org/2/library/os.html#os.listdir你需要FULLPATH打开文件。在打开它之前,请确保它是一个文件。下面的示例代码。

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 

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