如何在复制文件时将文件复制到python文件夹中
我正在用python编写一个脚本来将不同文件夹中的图像合并到一个文件夹中。可能存在多个具有相同名称的图像文件。如何在python中处理这个问题?我需要像这样将它们重命名为“image_name_0001”,“image_name_0002”。如何在复制文件时将文件复制到python文件夹中
您可以保留一个dict
到目前为止已经看到的名称数,然后使用os.rename()
将文件重命名为这个新名称。
例如:
dic = {}
list_of_files = ["a","a","b","c","b","d","a"]
for f in list_of_files:
if f in dic:
dic[f] += 1
new_name = "{0}_{1:03d}".format(f,dic[f])
print new_name
else:
dic[f] = 0
print f
输出:
a
a_001
b
c
b_001
d
a_002
这有助于我做一次。但是因为我需要做很多次,所以dic = {}会使它每次都为零。那么任何替代方案 – Sudhi1509 2013-06-13 10:27:56
@ Sudhi1509你是什么意思我的“做很多次”? 'dic = {}'应该在顶部(在循环之前)。 – 2013-06-13 10:38:15
如果有根的文件名,即名称= 'IMAGE_NAME',延伸,延长=名为.jpg和路径到输出文件夹,路径,你可以这样做:
*for each file*:
moved = 0
num = 0
if os.path.exists(path + name + ext):
while moved == 0:
num++
modifier = '_00'+str(num)
if not os.path.exists(path + name + modifier + extension):
*MOVE FILE HERE using (path + name + modifier + extension)*
moved = 1
else:
*MOVE FILE HERE using (path + name + ext)*
有obvio在这里有几个伪代码,但你应该得到的主意
你的问题是什么函数用于重命名或如何生成专有名称? – 2013-05-14 15:23:11