gpt4 book ai didi

Python:创建文本文件,写入,替换字符串

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

我正在创建一个文件,写入它,然后我想替换一个字符串。我有一切工作,除了更换。 re.sub、str.replace等我都试过了,想不通。

target_string = 'foo4bar44foobar444foobar, foo4bar'
file = open(source_file, "w+")
file.write(target_string)
target_string = re.sub('4', '55', target_string)

Desired Output: foo55bar5555foobar555555foobar, foo55bar

谢谢。

最佳答案

你所犯错误的官方术语是你的代码sequencing

在执行 re.sub 之前,您将 target_string 写入您的文件!您需要切换这些操作,以便将修改后的 stringwritefile:

target_string = 'foo4bar44foobar444foobar, foo4bar'
file = open(source_file, "w+")
target_string = re.sub('4', '55', target_string)
file.write(target_string)

此外,当您使用文件时,理想情况下您应该使用with语句,就像程序在您调用之前抛出一个错误一样file.close()(我假设你稍后会这样做),你会导致问题。

因此,您的最终代码应该类似于:

target_string = 'foo4bar44foobar444foobar, foo4bar'
with open(source_file, "w+") as f:
target_string = re.sub('4', '55', target_string) #could be moved out of with
file.write(target_string)

关于Python:创建文本文件,写入,替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47291973/

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