小编Sup*_*ter的帖子

替换文件名的子串

抱歉,如果之前已经问过这个问题。我没有通过搜索找到答案。需要在 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)

python replace substring rename

0
推荐指数
1
解决办法
1万
查看次数

标签 统计

python ×1

rename ×1

replace ×1

substring ×1