2017-03-18 217 views
0
import time, os 

timestamp = time.strftime('%d.%m_%H:%M') 

while True: 
    print("Beginning checkup") 
    print("=================") 
    for fname in os.listdir("C:/SOURCE"): 
     if fname.endswith(".txt"): 
      print("found " + fname) 
      os.rename(fname, fname.replace(fname, timestamp + ".txt")) 
      time.sleep(5) 

這是我的代碼。它應該做的是在SOURCE中查找.txt文件,併爲該名稱添加時間戳。這不知何故給了我一個「FileNotFoundError」。任何人有想法?用Python重命名文件似乎不起作用(os.rename)

+1

Windows不能有冒號':'在文件名中。 – Pit

回答

1

幾個問題

  • os.listdir返回文件名,不帶路徑。
  • 時間戳有一個:,你不能使用它作爲文件名
  • 你重命名你的文件到同一個,因爲你的替代工作不正常!

所以重命名時,你必須使用os.path.join提供給os.rename()

完整路徑的下一個問題是,您的更換添加時間戳錯誤。它不添加時間戳,但完全替換文件名。

fname.replace(fname, timestamp + ".txt")) 

嚴格相當於

timestamp + ".txt" 

另一個小問題是,如果一個文件.TXT結束它不是由你的過濾檢測。對於複雜的通配符,最好使用fnmatch模塊。就你而言,我只是申請lower()

我的完整修復的建議,這將插入你的目錄下的所有txt文件時間戳:

timestamp = time.strftime('%d_%m_%H_%M') # only underscores: no naming issues 
the_dir = "C:/SOURCE" 
for fname in os.listdir(the_dir): 
    if fname.lower().endswith(".txt"): 
     print("found " + fname) 
     new_name = "{}_{}.txt".format(os.path.splitext(fname)[0],timestamp) 
     os.rename(os.path.join(the_dir,fname), os.path.join(the_dir,new_name)) 

當然你也可以os.chdir正確的目錄中,但不是在複雜的應用程序,因爲建議這可能會破壞應用程序的其他部分。

你可能更喜歡另一種計算絕對路徑&過濾器只在txt文件使用glob

import glob 

for fname in glob.glob(os.path.join("C:/SOURCE","*.txt")): 
    # now fname bears the absolute path 
+0

該死的看起來合乎邏輯,我要去看看。 – diatomym

+0

似乎工作,但路徑格式似乎是用於Linux,因爲它將//添加到不適用於Windows的路徑。我如何解決這個問題? – diatomym

+0

路徑格式在Windows上正常工作。你可以說得更詳細點嗎? –