gpt4 book ai didi

Python:将字符串替换为文件中的变量

转载 作者:太空宇宙 更新时间:2023-11-03 11:21:24 33 4
gpt4 key购买 nike

如果我有这样一个文件内容:

old_string
-old_string

我只想将“old_string”更改为“+new_string”,所以结果看起来像

+new_string
-old_string

我的代码给出了这个结果:

+new_string
-+new_string

这是我的代码:

    with open(filename) as f:

s = f.read()

if old_string not in s:

return False

with open(filename, 'w') as f:

s = s.replace(old_string, new_string)

f.write(s)

return True

我试过正则表达式,但它不会工作,因为我将正则表达式作为变量传递,这就是我到目前为止所做的:

    with open (filename, 'r' ) as f:

content = f.read()

content_new = re.sub('(\%old_string)', r'\new_string'%(old_string,new_string), content, flags = re.M)

最佳答案

您可以忽略开头带有连字符(“-”)的行,并替换其余部分。

下面的脚本与您的略有不同。我已发表评论以帮助您理解。这应该很容易理解。

filename ="some_file"
output_filename = "some_other_file"

old_string = "old_string"
new_string = "+new_string"

input_file_handle = open(filename,"r") # File being opened in read mode
output_file_handle = open(output_filename, "w") # File being opened in write mode

# Read in input file line by line
for line in input_file_handle:

# Write to output file and move on to next line
if old_string not in line:
output_file_handle.write(line+"\n")
continue

# This line contains the old_string. We check if it starts with "-".
# If it does, write original line and move on to next line
if line.startswith("-"):
output_file_handle.write(line+"\n")
continue


# At this stage we are absolutely sure we want to replace this line's contents
# So we write the replaced version to the new file
output_file_handle.write(new_string+"\n")


# Close both file handles
input_file_handle.close()
output_file_handle.close()

关于Python:将字符串替换为文件中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42316730/

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