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

3 投票
2 回答
8879 浏览
提问于 2025-04-17 13:27

我想写一个程序,问你想替换什么,以及想用什么来替换。

我有一堆不同扩展名的文件,我想替换文件名中的某些部分,但我想替换的部分都是一样的。我想对文件夹里的每个文件都这样做。

所以我有这样的文件:

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

我只想把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")

2 个回答

0
import os

def rename(path,oldstr,newstr):
    for files in os.listdir(path):
        os.rename(os.path.join(path, files), os.path.join(path, files.replace(oldstr, newstr)))

使用这个可以轻松完成你的工作

3

你可能需要添加一些东西,但这里是基本的想法:

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机器上),你可以使用相对路径。

根据文档

os.replace(src, dst, *, src_dir_fd=None, dst_dir_fd=None)可以支持指定src_dir_fd和/或dst_dir_fd,这样就可以提供相对于目录描述符的路径

撰写回答