用于排序和重命名文件的 Python 脚本 - 删除重复项
我编写了一个小脚本,需要在该脚本所在的同一文件夹中对文件进行重命名和排序。它根据文件的最后修改将文件重命名为整数(1、2、3、4...):
import os
import sys
def gtime(nam):
return os.path.getmtime('./'+nam)
files = os.listdir('.')
files.remove(str(sys.argv[0])[2:])
files = sorted(files, key=gtime)
for fi in range(len(files)):
os.rename('./'+files[fi], './'+str(fi+1))
这是我想出的最好的方法...问题是当存在重复项时(例如,一个已命名为 1 的文件,可能来自以前的排序)它只是将其删除。.我怎样才能防止这种情况发生?我可以对代码进行任何修改或更好的替代方法吗???
I've written a small script that I needed to rename and sort files in the same folder where the script is. It renames the files into integers (1, 2, 3, 4, ...) based on the last modification of files:
import os
import sys
def gtime(nam):
return os.path.getmtime('./'+nam)
files = os.listdir('.')
files.remove(str(sys.argv[0])[2:])
files = sorted(files, key=gtime)
for fi in range(len(files)):
os.rename('./'+files[fi], './'+str(fi+1))
That was the best I've come up with to do so... The problem is when there's a duplicate (e.g. a file already named 1, maybe from a previous sort) it just removes it.. How can I prevent this from happening?? Is there any modification I can do to the code or a better alternative way???
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因此,这里有一个示例,它将复制到子目录并避免复制脚本的
.pyc
文件。So here's an example that will copy to a subdirectory and avoid copying your script's
.pyc
file as well.您无法一个接一个地重命名文件,因为在此过程中您可能会覆盖已排序的文件。但是,您可以先使用临时名称,然后在第二遍中将文件重命名为其最终名称:(
未经测试)
You can't rename one file after the other, as you might overwrite already sorted files during the process. You can however use temporary names first and then rename the files to their final names in a second pass:
(untested)