【问题标题】:How to multiplely modify one piece of the file name in python如何在python中多次修改一个文件名
【发布时间】:2022-01-06 00:21:28
【问题描述】:

新学员。我在一个文件夹中有几个 txt 文件。我需要将“April”更改为“APR”。

12 April 2019 Nmae's something Something.txt

13 April 2019 World's - as Countr something.txt

14 April 2019 Name and location.txt

15 APR 2019 Name then location,for something.txt

原来是这样的

12 APR 2019 Nmae's something Something.txt

13 APR 2019 World's - as Countr something.txt

14 APR 2019 Name and location.txt

15 APR 2019 Name then location,for something.txt

这里有相似的链接,但每个链接都略有不同。

Python - Replace multiple characters in one file name

CHange multiple file name python

PYTHON - How to change one character in many file names within a directory

How to change multiple filenames in a directory using Python

我试过了:

import os
files = os.listdir('/home/runner/Final/foldername')
   for f in files:
newname = f.replace('April', 'APR')
os.rename(f, newname)

但没有任何变化,我可以得到一些指导吗?

【问题讨论】:

  • 这可能与您的工作目录有关。当您致电os.rename(f, ...) 时,它需要知道f 在哪里。通过os.path.join('/home/runner/Final/foldername', f) 提供完整路径可能会有所帮助。我不确定您是否还需要使用os.path.join('/home/runner/Final/foldername', newname)

标签: python rename filenames


【解决方案1】:

问题在于 f 只是文件名,而不是完整路径,因此您的命令 os.rename(f, newname) 将重命名当前工作目录中名为 f 的文件,而不是目标目录。此外,您会尝试重命名每个文件,而不仅仅是实际更改的文件。

这里有一些更好的东西:

from pathlib import Path


for f in Path('/home/runner/Final/foldername').glob('*'):
    if f.is_file():
        new_name = f.name.replace('April', 'APR')
        if new_name != f.name:
            f.rename(Path('/home/runner/Final/foldername') / new_name)

它还会检查找到的内容是否实际上是一个文件(否则,它会包含目录,并且您似乎不想重命名这些目录)。

请注意,在最新版本的 Python 中,这也有效:

for f in Path('/home/runner/Final/foldername').glob('*'):
    if f.is_file():
        if (new_name := f.name.replace('April', 'APR')) != f.name:
            f.rename(Path('/home/runner/Final/foldername') / new_name)

为了避免不断地重构 Path 对象:

folder = Path('/home/runner/Final/foldername')

for f in folder .glob('*'):
    if f.is_file():
        if (new_name := f.name.replace('April', 'APR')) != f.name:
            f.rename(folder / new_name)

【讨论】:

    猜你喜欢
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-18
    • 1970-01-01
    • 2017-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多