簡體   English   中英

使用Python重命名文件似乎不起作用(os.rename)

[英]Renaming files with Python doesn't seem to work (os.rename)

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”。 有人有主意嗎?

幾個問題

  • 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轉到正確的目錄,但是在復雜的應用程序中不建議這樣做,因為這可能會破壞應用程序的其他部分。

您可能更喜歡使用glob僅在txt文件上計算絕對路徑和過濾器的替代方法

import glob

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

暫無
暫無

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

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