替换文件名的子串

Sup*_*ter 0 python replace substring rename

抱歉,如果之前已经问过这个问题。我没有通过搜索找到答案。需要在 Python 中替换文件名的子字符串。

旧字符串:“_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")
Run Code Online (Sandbox Code Playgroud)

Art*_* B. 8

另一个答案告诉你,你可以用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")
Run Code Online (Sandbox Code Playgroud)

您的代码的问题在于 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))
Run Code Online (Sandbox Code Playgroud)