gpt4 book ai didi

python3.5.2 从文件中删除所有匹配的字符

转载 作者:太空宇宙 更新时间:2023-11-04 09:52:06 25 4
gpt4 key购买 nike

给定以下示例,我如何从具有以下内容的文件中删除所有“a”字符:

asdasdasd \n d1233sss \n aaa \n 123

我编写了以下解决方案,但它不起作用:

with open("testfisier","r+") as file:
for line in file:
for index in range(len(line)):
if line[index] is "a":line[index].replace("a","")

最佳答案

没有任何更改,因为您没有将其写回文件。

with open("testfisier", "r+") as file:
for line in file:
for index in range(len(line)):
if line[index] is "a":
replace_file = line[index].replace("a", "")

# Write the changes.
file.write(replace_file)

或者:

with open("testfisier", "r+") as f:
f.write(f.read().replace("a", ""))

关于python3.5.2 从文件中删除所有匹配的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47367779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com