2013-08-22 41 views
9

我需要從不同目錄中打開一個文件,而不必使用它的路徑,而停留在當前目錄中。打開不同目錄中的所有文件python

當我執行下面的代碼:

for file in os.listdir(sub_dir): 
    f = open(file, "r") 
    lines = f.readlines() 
    for line in lines: 
     line.replace("dst=", ", ") 
     line.replace("proto=", ", ") 
     line.replace("dpt=", ", ") 

我得到錯誤信息FileNotFoundError: [Errno 2] No such file or directory:,因爲它是在一個子目錄。

問題:是否有一個os命令我可以使用它將找到並打開文件sub_dir

謝謝! - 我知道這是否是重複的,我搜索了並找不到一個,但可能錯過了它。

+0

您需要將sub_dir路徑添加到在open()函數的文件能夠打開它來複制文件。 – 2013-08-22 20:14:42

回答

11

os.listdir()列表只有沒有路徑的文件名。與sub_dir再在前面加上這些:

for filename in os.listdir(sub_dir): 
    f = open(os.path.join(sub_dir, filename), "r") 

如果你正在做的是循環遍歷從文件,在文件本身只是環行;使用with確保文件在完成時也關閉。最後但並非最不重要的,str.replace()回報新的字符串值,不改變本身的價值,所以你需要存儲返回值:

for filename in os.listdir(sub_dir): 
    with open(os.path.join(sub_dir, filename), "r") as f: 
     for line in f: 
      line = line.replace("dst=", ", ") 
      line = line.replace("proto=", ", ") 
      line = line.replace("dpt=", ", ") 
+0

如果我想將新行寫入'filename',我會添加'f.write(line)'並以'a'模式打開嗎? – hjames

+0

@hjames:當然,只需調整'open()'調用的'mode'參數即可。 –

+0

嗯,如果我把它放在'a'或'w'模式下,它會返回一個文件不可讀的錯誤。如果我把它放在'r'模式下,它顯然不能寫入文件。 – hjames

10

如果這些文件不在當前必須給出完整路徑目錄:

f = open(os.path.join(sub_dir, file)) 

我不會用file作爲變量名,也許filename,因爲這是用來在Python中創建一個文件對象。

-1

代碼中使用shutil

import shutil 
import os 

source_dir = "D:\\StackOverFlow\\datasets" 
dest_dir = "D:\\StackOverFlow\\test_datasets" 
files = os.listdir("D:\\StackOverFlow\\datasets") 

if not os.path.exists(dest_dir): 
    os.makedirs(dest_dir) 

for filename in files: 
    if file.endswith(".txt"): 
     shutil.copy(os.path.join(source_dir, filename), dest_dir) 

print os.listdir(dest_dir) 
相關問題