python:根据修改日期+迭代器重命名文件

时间:2012-09-12 23:54:01

标签: python

我有一个不断添加的文件目录。有时候每天都有几个文件,但数量可能会有所不同。我想定期运行一个脚本来扫描文件并根据文件创建日期重命名它们+如果当天有多个文件则重命名一些脚本。

这是我到目前为止所做的事情

#!/usr/bin/python
import os
import datetime
target = "/target_dir"
os.chdir(target)
allfiles = os.listdir(target)
for filename in allfiles:
        if not os.path.isfile(filename):
                continue
        t = os.path.getmtime(filename)
        v= datetime.datetime.fromtimestamp(t)
        x = v.strftime('%Y%m%d')
        loop = 1
        iterator = 1
        temp_name = x + "_" + str(iterator)
        while loop:
                if not os.path.exists(temp_name + '.mp4'):
                        os.rename(filename, temp_name + '.mp4')
                        loop = 0
                else:
                        temp_name = x + '_' + str(iterator)
                        iterator+=1

这似乎有效但是如果我第二次运行脚本它会过早地更改文件名(即date1-1.mp4变为date1-2.mp4等)

有什么建议吗?

2 个答案:

答案 0 :(得分:2)

添加额外支票if filename == tempname: continue

答案 1 :(得分:1)

当您第一次重命名文件时,您就会拥有一个文件夹: date1-1.mp4,date2-1.mp4 ,正如您所说。

在第二次运行时,行if not os.path.exists(temp_name + '.mp4'):将表示文件 date1-1.mp4 已经存在 - 即文件本身 - 然后将继续循环,直到未使用的文件名为可用: date1-2.mp4

我的解决方案如下:(基本上相当于Hans的回答)

#!/usr/bin/python
import os
import datetime
target = + "/target_dir"
os.chdir(target)
allfiles = os.listdir(target)
for filename in allfiles:
    if not os.path.isfile(filename):
        continue
    t = os.path.getmtime(filename)
    v= datetime.datetime.fromtimestamp(t)
    x = v.strftime('%Y%m%d')
    loop = 1
    iterator = 1
    temp_name = x + "_" + str(iterator) + '.mp4'

    while filename != temp_name:
        if not os.path.exists(temp_name):
            os.rename(filename, temp_name)
            filename = temp_name
        else:
            iterator+=1
            temp_name = x + '_' + str(iterator) + '.mp4'
相关问题