【问题标题】:Python, I want to replace parts of filenames for a group of filesPython,我想为一组文件替换部分文件名
【发布时间】:2013-01-07 12:39:53
【问题描述】:

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

我有一大组具有不同扩展名的文件,我想替换部分文件名,但我要替换的所有部分都是相同的。我想对文件夹中的每个文件都这样做

所以我有类似的文件

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")

【问题讨论】:

  • 使用str.replace(),这是你的全部代码吗?
  • 您要对目录中的所有文件执行此操作,还是对目录中的文件执行此操作?
  • 除了@AshwiniChaudhary,您可能还需要使用os.listdir 来获取目录中的文件列表。
  • 如果你使用*nix,你可以试试mmv命令

标签: python file rename


【解决方案1】:
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)))

使用它可以轻松完成您的工作

【讨论】:

    【解决方案2】:

    您可能需要添加一些东西,但基本思路如下:

    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)))
    

    编辑:正如 cmets 中的 @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

    【讨论】:

    • 你可能想把os.path.join(directory, f)放在某个地方。
    • 不,不会。 os.listdir() 函数只返回文件名,而不是完整路径。 os.rename() 函数需要完整的路径。
    • @DietrichEpp -- 好吧,我只是在 linux 机器上试了一下,它似乎工作正常......但如果文件不在路径上,则无法工作,是的,将编辑。
    • @root:如果directory 不是当前工作目录,请尝试运行它。无关:在 Python 3.3 上,您可以使用相对路径并覆盖现有文件:os.replace(f, f.replace(old, new), src_dir_fd=dir_fd, dst_dir_fd=dir_fd)
    • @J.F.Sebastian:我猜src_dir_fd 关键字只能在支持最近添加的 POSIX 的系统上工作,比如 Linux(但不包括 OS X、Windows)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多