gpt4 book ai didi

Python,我想替换一组文件的部分文件名

转载 作者:行者123 更新时间:2023-11-30 23:38:27 25 4
gpt4 key购买 nike

我想编写一个程序,询问您要替换什么以及用什么替换它。

我有一大组具有不同扩展名的文件,我想替换部分文件名,但我想替换的所有部分都是相同的。我想对文件夹中的每个文件执行此操作

所以我有类似的文件

ABC.txt
gjdABCkg.txt
ABCfg.jpg
ffABCff.exe

我只想用我想要的 3 个字母替换 ABC我正在使用 python 3.2

我正在闲逛,看看是否可以让它工作,但我所做的一切都不起作用这就是我到目前为止所拥有的。

import os  

directory = input ("Enter your directory")
old = input ("Enter what you want to replace ")
new = input ("Enter what you want to replace it with")

最佳答案

您可能需要添加一些内容,但基本思想如下:

import os

def rename(path,old,new):
for f in os.listdir(path):
os.rename(os.path.join(path, f),
os.path.join(path, f.replace(old, new)))

编辑:正如 @J.F Sebastian 在评论中指出的,您可以使用 Python 3.3 中的相对路径(至少在 Linux 计算机上)。

来自docs :

os.replace(src, dst, *, src_dir_fd=None, dst_dir_fd=None) 可以支持指定 src_dir_fd 和/或 dst_dir_fd供应paths relative to directory descriptors .

关于Python,我想替换一组文件的部分文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14489801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com