2 回答
TA贡献2036条经验 获得超8个赞
我理解你的问题,看起来你想编辑你的 hello.text 文件,并且 .txt 包含一些字符('d)并且你想用任何字符串替换它。所以你可以做这样的事情,
# Read in the file
with open('hello.txt', 'r') as file :
filedata = file.read()
# Replace the target string
filedata = filedata.replace('d', 'abcd')
# Write the file out again
with open('hello.txt', 'w') as file:
file.write(filedata)
TA贡献1943条经验 获得超7个赞
就这样吧。(尝试理解我做了什么 - 这很容易 - 如果你没有得到任何结果,请发表评论..)
def main():
with open("test.txt", "r") as f:
fileData = f.read()
print(fileData)
a = [char for char in fileData]
for i in range(len(a)):
if a[i] == 'd':
a[i] = 'LoL'
else:
continue
with open("test.txt", "w") as f:
f.write(''.join(a))
if __name__=="__main__":
main()
添加回答
举报