Skip to main content
 首页 » 编程设计

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

2025年05月04日23bonelee

我正在创建一个文件,写入它,然后我想替换一个字符串。我有一切工作,除了更换。 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 写入您的文件!您需要切换这些操作,以便将修改后的 stringwrite 到 file:

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)