如何替换目录中每个文件中的字符串

2024-10-02 16:21:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用python替换一个字符串:“xxxxxxxxxx”和一个新的字符串:“ILoveStackOverflow”在特定文件夹中的每个文件中(文件夹中的所有文件都是xml)。你知道吗

我的代码如下:

import os, fnmatch

for filename in os.listdir("C:/Users/Francesco.Borri/Desktop/passivo GME"):
if filename.endswith('.xml'):
    with open(os.path.join("C:/Users/Francesco.Borri/Desktop/passivo GME", filename)) as f: 
        content = f.read()
        content = content.replace("XXXXXXXXXXX", "ILoveStackOverflow")
    with open(os.path.join("C:/Users/Francesco.Borri/Desktop/passivo GME", filename), mode="w") as f: #Long Pierre-André answer
        f.write(content)

下一步是用一个每次递增的数字替换另一个字符串:“YYYY”。如果在我的目录中有10个文件,并且我将起始编号设置为1,则第一个文件“YYYY”将替换为1,第二个文件将替换为2,依此类推直到10。你知道吗


Tags: 文件字符串文件夹oswithxmlcontentfilename
2条回答

你很接近。第二次打开文件时,必须以可写模式打开才能写入内容。你知道吗

with open(os.path.join("C:/Users/Francesco.Borri/Desktop/passivo GME", filename), 'w') as f:
    f.write(content)

一旦解决了这个问题,我认为问题的第二部分就是维护一个变量,每次替换字符串时,该变量的值都会递增。您可以手动执行(遍历字符串),或在for循环中使用replace函数:

with open(os.path.join("C:/Users/Francesco.Borri/Desktop/passivo GME", filename)) as f:
        content = f.read()
for i in range(content.count("YYYY")):
    content.replace("YYYY", str(i), 1)  # or str(i+1)
with open(os.path.join("C:/Users/Francesco.Borri/Desktop/passivo GME", filename), 'w') as f:
        f.write(content)
with open(os.path.join("C:/Users/Francesco.Borri/Desktop/passivo GME", filename), mode="w") as f:

必须以写入模式打开文件。你知道吗

相关问题 更多 >