【发布时间】: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)。