替换文件名的子字符串

0 投票
5 回答
16123 浏览
提问于 2025-04-18 15:20

抱歉,如果这个问题之前有人问过。我搜索的时候没有找到答案。

旧字符串: "_ready"

新字符串: "_busy"

文件名: a_ready.txt, b_ready.txt, c.txt, d_blala.txt, e_ready.txt

输出结果: a_busy.txt, b_busy.txt, c.txt, d_blala.txt, e_busy.txt

有什么好主意吗?我试过用replce(),但是没有任何效果。文件名还是老的。

这是我的代码:

import os

counter = 0

for file in os.listdir("c:\\test"):
    if file.endswith(".txt"):
        if file.find("_ready") > 0:
            counter = counter + 1
            print ("old name:" + file)
            file.replace("_ready", "_busy")
            print ("new name:" + file)
if counter == 0:
    print("No file has been found")

5 个回答

0

像这样:

old_string = "a_ready"
new_string = old_string.replace('_ready', '_busy')
0

你也可以这样做(如果这个字符串是固定的):

old_string = "a_ready"
new_string = old_string[:1]+"_busy"

不过我觉得@Selva有更好的方法。

0

你需要用的是 string.replace() 这个方法

你可以在 这里 查看,信息就在页面底部

你可以这样使用

for file in files:
    output.append( file.replace(oldString, newString) )
1
from os import rename, listdir

fnames = listdir('.')
for fname in fnames:
    if fname.endswith('.txt'):
        new_name = fname.replace('_ready', '_busy')
        rename(fname, new_name)

这可能就是你需要的。不过我还是不太明白你的意思。

12

之前的回答已经告诉你,可以用 string.replace 来替换字符串中的一部分。你需要的是 os.rename

import os
counter = 0
path = "c:\\test"
for file in os.listdir(path):
    if file.endswith(".txt"):
        if file.find("_ready") > -1:
            counter = counter + 1
            os.rename(os.path.join(path, file), os.path.join(path, file.replace("_ready", "_busy")))
if counter == 0:
    print("No file has been found")

你代码的问题在于,Python中的字符串是不可变的,也就是说,使用 replace 方法会返回一个新的字符串,而不是修改原来的字符串。如果你想在后面使用这个新字符串,就得把它替换掉当前的 file,并把它添加到一个列表中:

files = [] # list of tuple with old filename and new filename
for file in os.listdir(path):
    if file.endswith(".txt"):
        if file.find("_ready") > -1:
            counter = counter + 1
            newFileName = file.replace("_ready", "_busy"))
            files.append((file, newFileName))

撰写回答