如果文本文件中包含用户在 Python 中输入的某个字符串,如何更新文本文件中的一行?
How would update a line in a text file if it contains a certain string with user input in Python?
目前我有一个接受文本文件作为设置参数的程序。文本文件的格式如下:
我想在 Python 中做的是能够解析文件。我想阅读每一行并检查它是否包含特定的字符串,如果该行包含它,则能够 append/update 将用户输入文本放在该行的末尾。
例如,在文本文件中找到 "PRIMER_PRODUCT_SIZE_RANGE="(突出显示),我想将其从 "PRIMER_PRODUCT_SIZE_RANGE=100-300" 更新为例如 "PRIMER_PRODUCT_SIZE_RANGE=500-1000"。我希望能够对几个参数(我根据需要选择的)执行此操作。
我研究过的一些工具包括 fileinput 模块,执行常规文件 open/write(显然我无法进行就地编辑),以及我发现的一个名为 in_place module.
我使用 in_place 模块的一些初步代码:
def SettingFileParser(filepath):
with in_place.InPlaceText(filepath) as text_file:
for line in text_file:
if 'PRIMER_PRODUCT_SIZE_RANGE=' in line:
text_file.write("idk what to put here")
我是一个菜鸟程序员,所以任何正确方向的帮助或指导都将不胜感激。
您需要打开文件进行读取(默认),然后您需要打开一个文件进行写入:
def SettingFileParser(filepath):
with open(filepath, 'r') as read_file:
lines = read_file.readlines():
with open(filepath, 'w') as write_file:
for line in lines:
if line.startswith('PRIMER_PRODUCT_SIZE_RANGE='):
# keep the line the same except the part needing replacement
write_file.write(line.replace('100-300','500-1000'))
else:
# otherwise just write the line as is
write_file.write(line)
对于此任务,regular expressions are the way to go. I refer you to this post。
具体来说,这样的事情可能会成功:
import re
# read in file here...
re.sub(r"PRIMER_PRODUCT_SIZE_RANGE=[0-9,-]*", "PRIMER_PRODUCT_SIZE_RANGE=500-1000", s)
此处,s
将是文本文件中的整个字符串。
您可以将 re
用于 changing/manipulating 个字符串 (explanation of this regex on external site):
data = """
# PRIMER_PRODUCT_SIZE_RANGE=xxx-yyy
PRIMER_PRODUCT_SIZE_RANGE=100-300
PRIMER_NUM_RETURN=3
PRIMER_MAX_END_STABILITY=9.0
PRIMER_MAX_HAIRPIN_TH=24.0
"""
import re
def change_parameter(data, parameter, new_value):
return re.sub(r'^(\s*(?<!#)\s*{}\s*)=.*$'.format(parameter), r'={}'.format(new_value), data, flags=re.M|re.I)
data = change_parameter(data, 'PRIMER_PRODUCT_SIZE_RANGE', '100-500')
data = change_parameter(data, 'PRIMER_MAX_HAIRPIN_TH', '99.9')
print(data)
这会打印:
# PRIMER_PRODUCT_SIZE_RANGE=xxx-yyy
PRIMER_PRODUCT_SIZE_RANGE=100-500
PRIMER_NUM_RETURN=3
PRIMER_MAX_END_STABILITY=9.0
PRIMER_MAX_HAIRPIN_TH=99.9
要 reading/writing 提交,您可以使用此代码段:
with open('parameters.txt', 'r', newline='') as f_in:
data = f_in.read()
with open('parameters.txt', 'w', newline='') as f_out:
data = change_parameter(data, 'PRIMER_PRODUCT_SIZE_RANGE', '100-500')
data = change_parameter(data, 'PRIMER_MAX_HAIRPIN_TH', '99.9')
f_out.write(data)
编辑:
change_parameter()
的扩展版本:
import re
data = """
PRIMER_PRODUCT_SIZE_RANGE=100-500 200-400
PRIMER_NUM_RETURN=3
PRIMER_MAX_END_STABILITY=9.0
"""
def change_parameter_ext(data, parameter, old_value, new_value):
def _my_sub(g):
return g[1] + '=' + re.sub(r'{}'.format(old_value), new_value, g[2], flags=re.I).strip()
return re.sub(r'^(\s*(?<!#)\s*{}\s*)=(.*)$'.format(parameter), _my_sub, data, flags=re.M|re.I).strip()
data = change_parameter_ext(data, 'PRIMER_PRODUCT_SIZE_RANGE', '200-400', '500-600')
data = change_parameter_ext(data, 'PRIMER_NUM_RETURN', '3', '100-200 300-400')
print(data)
打印:
PRIMER_PRODUCT_SIZE_RANGE=100-500 500-600
PRIMER_NUM_RETURN=100-200 300-400
PRIMER_MAX_END_STABILITY=9.0
目前我有一个接受文本文件作为设置参数的程序。文本文件的格式如下:
我想在 Python 中做的是能够解析文件。我想阅读每一行并检查它是否包含特定的字符串,如果该行包含它,则能够 append/update 将用户输入文本放在该行的末尾。
例如,在文本文件中找到 "PRIMER_PRODUCT_SIZE_RANGE="(突出显示),我想将其从 "PRIMER_PRODUCT_SIZE_RANGE=100-300" 更新为例如 "PRIMER_PRODUCT_SIZE_RANGE=500-1000"。我希望能够对几个参数(我根据需要选择的)执行此操作。
我研究过的一些工具包括 fileinput 模块,执行常规文件 open/write(显然我无法进行就地编辑),以及我发现的一个名为 in_place module.
我使用 in_place 模块的一些初步代码:
def SettingFileParser(filepath):
with in_place.InPlaceText(filepath) as text_file:
for line in text_file:
if 'PRIMER_PRODUCT_SIZE_RANGE=' in line:
text_file.write("idk what to put here")
我是一个菜鸟程序员,所以任何正确方向的帮助或指导都将不胜感激。
您需要打开文件进行读取(默认),然后您需要打开一个文件进行写入:
def SettingFileParser(filepath):
with open(filepath, 'r') as read_file:
lines = read_file.readlines():
with open(filepath, 'w') as write_file:
for line in lines:
if line.startswith('PRIMER_PRODUCT_SIZE_RANGE='):
# keep the line the same except the part needing replacement
write_file.write(line.replace('100-300','500-1000'))
else:
# otherwise just write the line as is
write_file.write(line)
对于此任务,regular expressions are the way to go. I refer you to this post。
具体来说,这样的事情可能会成功:
import re
# read in file here...
re.sub(r"PRIMER_PRODUCT_SIZE_RANGE=[0-9,-]*", "PRIMER_PRODUCT_SIZE_RANGE=500-1000", s)
此处,s
将是文本文件中的整个字符串。
您可以将 re
用于 changing/manipulating 个字符串 (explanation of this regex on external site):
data = """
# PRIMER_PRODUCT_SIZE_RANGE=xxx-yyy
PRIMER_PRODUCT_SIZE_RANGE=100-300
PRIMER_NUM_RETURN=3
PRIMER_MAX_END_STABILITY=9.0
PRIMER_MAX_HAIRPIN_TH=24.0
"""
import re
def change_parameter(data, parameter, new_value):
return re.sub(r'^(\s*(?<!#)\s*{}\s*)=.*$'.format(parameter), r'={}'.format(new_value), data, flags=re.M|re.I)
data = change_parameter(data, 'PRIMER_PRODUCT_SIZE_RANGE', '100-500')
data = change_parameter(data, 'PRIMER_MAX_HAIRPIN_TH', '99.9')
print(data)
这会打印:
# PRIMER_PRODUCT_SIZE_RANGE=xxx-yyy
PRIMER_PRODUCT_SIZE_RANGE=100-500
PRIMER_NUM_RETURN=3
PRIMER_MAX_END_STABILITY=9.0
PRIMER_MAX_HAIRPIN_TH=99.9
要 reading/writing 提交,您可以使用此代码段:
with open('parameters.txt', 'r', newline='') as f_in:
data = f_in.read()
with open('parameters.txt', 'w', newline='') as f_out:
data = change_parameter(data, 'PRIMER_PRODUCT_SIZE_RANGE', '100-500')
data = change_parameter(data, 'PRIMER_MAX_HAIRPIN_TH', '99.9')
f_out.write(data)
编辑:
change_parameter()
的扩展版本:
import re
data = """
PRIMER_PRODUCT_SIZE_RANGE=100-500 200-400
PRIMER_NUM_RETURN=3
PRIMER_MAX_END_STABILITY=9.0
"""
def change_parameter_ext(data, parameter, old_value, new_value):
def _my_sub(g):
return g[1] + '=' + re.sub(r'{}'.format(old_value), new_value, g[2], flags=re.I).strip()
return re.sub(r'^(\s*(?<!#)\s*{}\s*)=(.*)$'.format(parameter), _my_sub, data, flags=re.M|re.I).strip()
data = change_parameter_ext(data, 'PRIMER_PRODUCT_SIZE_RANGE', '200-400', '500-600')
data = change_parameter_ext(data, 'PRIMER_NUM_RETURN', '3', '100-200 300-400')
print(data)
打印:
PRIMER_PRODUCT_SIZE_RANGE=100-500 500-600
PRIMER_NUM_RETURN=100-200 300-400
PRIMER_MAX_END_STABILITY=9.0