簡體   English   中英

無法從python目錄中打開文件

[英]Can't Open files from a directory in 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'

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

但是,對於文件,最好使用with關鍵字打開。 即使有例外,它也會為您處理關閉。 有關詳細信息和示例,請參見https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM