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

2024-10-01 09:22:14 发布

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

我正在创建一个文件,写入其中,然后我想替换一个字符串。我一切都在工作,除了替补。我试过了re.sub公司, 结构更换等等,我想不通。在

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

谢谢。在


Tags: 文件字符串resourcetargetoutputstring公司
3条回答

请尝试以下操作,在写入目标字符串之前执行替换并关闭文件:

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

OR

target_string = 'foo4bar44foobar444foobar, foo4bar'
with open(source_file,"w") as f:
  target_string = re.sub('4', '55', target_string)
  f.write(target_string)

你所犯错误的官方术语是你的codesequencing。在

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

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

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

所以,你最后的code应该看起来像:

^{pr2}$

您需要在写入文件之前更改字符串。在

切换最后两行。在

相关问题 更多 >