2014-09-26 116 views
2

我寫了一個小模塊,它首先找到目錄中的所有文件併合並它們。 但是,我遇到了從目錄中打開這些文件的問題。 我確信我的文件和目錄名是正確的,文件實際上在目錄中。無法從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

回答

4

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

相關問題