在Python中用新文件名替换文件名

1 投票
1 回答
1533 浏览
提问于 2025-04-16 17:40

可能重复的问题:
在Python中重命名文件

大家好,我正在用Python写一个脚本,目的是把一些和批量图片编辑相关的操作系统命令整合在一起。大部分任务都完成了,但我在一个看似简单的任务上遇到了麻烦。

当我用扫描仪扫描图片时,得到的文件名大概是这样的:

201105151110_0001A.jpg

文件名的前半部分是某种时间戳(我想把它替换掉),我希望能把这个部分变成一个输入变量,这样我自己或者其他用户就可以在命令行中粘贴这个内容,因为如果我用其他扫描仪,文件名的结构可能会不同。后面的0001A表示第一张照片或文件的正面,我想保留这个部分。

我设置了三个变量:

    old_prefix = input(bcolors.PROMPT + "Enter the prefix to replace: " + bcolors.ENDC)
    new_prefix = input(bcolors.PROMPT + "Enter the new prefix: " + bcolors.ENDC)
    working_directory

working_directory是代码其他部分中的一个变量,表示图片所在的目录。颜色部分只是为了让我能给输出上色,方便阅读。通常在我处理的时候,这个目录里会有1到1000个文件。

这个脚本将在Linux系统上运行。

谢谢大家!

---编辑---

抱歉浪费大家的时间,似乎我在Kiril Kirov链接的问题中忽略了一些信息。我写的代码可以正常工作:

elif retouch_option == "06":
    print(" ")
    old_prefix = input(bcolors.PROMPT + "Enter the prefix to replace: " + bcolors.ENDC)
    new_prefix = input(bcolors.PROMPT + "Enter the new prefix.......: " + bcolors.ENDC)
    print(bcolors.OUTPUT + " ")
    for fname in glob(working_directory + "*.jpg"):
        keeper = fname[-9:]
        print("Renaming image", keeper)
        os.rename(fname, fname.replace(old_prefix, new_prefix)) 

我觉得这样做应该是安全的,因为只是把old_prefix变量替换成new_prefix变量。这样做对吗?如果不对,我非常欢迎大家给我反馈,不过到目前为止,这个方法似乎运行得很好。

1 个回答

2

类似这样的内容:

sep = '_'
try:
    prefix,keeper = filename.split(sep)
except: # filename does not match desired structure
    print "not processed: no '" + sep + "' in '"+ filename + "'"
else:   # split succeeded: 
    if prefix == old_prefix:
        filename = new_prefix + sep + keeper
        # more processing...
    else:
        print "prefix doesn't match in '" + filename + "'"

撰写回答