2016-03-01 78 views
0

我做了一個簡單的程序來測試。它只是查找特定字符串的任何實例,並用新字符串替換它。我想要做的是對我的整個目錄,逐個文件地運行這個。在目錄上運行一個簡單的腳本

def replace(directory, oldData, newData): 
    for file in os.listdir(directory): 
     f = open(file,'r') 
     filedata = f.read() 
     newdata = filedata.replace(oldData,newData) 
     f = open(file, 'w') 
     f.write(newdata) 
     f.close() 

但我不斷收到一條錯誤消息,告訴我一個文件不存在於我的目錄中,即使它存在。我無法弄清楚爲什麼它會告訴我。

+3

'os.listdir'僅返回文件名,他們沒有目錄前綴。使用'os.path.join'連接它們。 – Barmar

回答

1

os.listdir()返回一個非常類似於終端命令ls的字符串列表。它列出了文件的名稱,但不包括目錄的名稱。您需要在自己加入與os.path.join()

def replace(directory, oldData, newData): 
    for file in os.listdir(directory): 
     file = os.path.join(directory, file) 
     f = open(file,'r') 
     filedata = f.read() 
     newdata = filedata.replace(oldData,newData) 
     f = open(file, 'w') 
     f.write(newdata) 
     f.close() 

我不會推薦file作爲變量名,但是,因爲它具有內置式衝突。另外,建議在處理文件時使用with塊。以下是我的版本:

def replace(directory, oldData, newData): 
    for filename in os.listdir(directory): 
     filename = os.path.join(directory, filename) 
     with open(filename) as open_file: 
      filedata = open_file.read() 
      newfiledata = filedata.replace(oldData, newData) 
      with open(filename, 'w') as write_file: 
       f.write(newfiledata) 
1

試試這個方法:

def replace(directory, oldData, newData): 
    for file in os.listdir(directory): 
     f = open(os.path.join(directory, file),'r') 
     filedata = f.read() 
     newdata = filedata.replace(oldData,newData) 
     f = open(os.path.join(directory, file), 'w') 
     f.write(newdata) 
     f.close() 
相關問題