简体   繁体   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)

This is the code I have. 这是我的代码。 What its supposed to do is look for .txt files in SOURCE and add a timestamp to the name. 它应该做的是在SOURCE中查找.txt文件,并在名称中添加一个时间戳。 This somehow gives me a "FileNotFoundError". 这以某种方式给了我一个“ FileNotFoundError”。 Anyone have an idea? 有人有主意吗?

Several problems 几个问题

  • os.listdir returns the filename, without the path. os.listdir返回文件名,不带路径。
  • timestamp has a : , you cannot use that as a file name 时间戳记带有: ,您不能将其用作文件名
  • you rename your files into the same one because your substitution isn't working properly! 您将文件重命名为同一文件,因为您的替换无法正常工作!

So when renaming you have to use os.path.join to provide full path to os.rename() 因此,重命名时必须使用os.path.join提供os.rename()完整路径。

The next issue is that your replacement to add a timestamp is wrong . 下一个问题是您替换添加时间戳的错误 It doesn't add the timestamp but replaces the filename completely. 它不添加时间戳,而是完全替换文件名。

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

is strictly equivalent to 严格等于

timestamp + ".txt"

Another minor issue is that if a file ends with .TXT it is not detected by your filter. 另一个小问题是,如果文件以.TXT结尾,则过滤器无法检测到该文件。 It's better to use fnmatch module for complex wildcards. 对于复杂的通配符,最好使用fnmatch模块。 In your case, I just applied lower() . 在您的情况下,我只是应用了lower()

my complete fix proposal, which inserts a timestamp on all txt files of your directory: 我的完整修复建议,该建议会在目录的所有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))

Of course you could also os.chdir to the proper directory, but that isn't advised in a complex application because that could break other parts of the application. 当然,您也可以将os.chdir转到正确的目录,但是在复杂的应用程序中不建议这样做,因为这可能会破坏应用程序的其他部分。

You may prefer an alternative to compute absolute path & filter only on txt files using glob 您可能更喜欢使用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