[英]Modify variable value in text file with python
我有一個包含以下內容的文本文件;
variable_1 = 1;
variable_2 = 2;
variable_3 = 3;
variable_4 = 4;
使用 python,我想將variable_2
修改為22
,將variable_3
修改為33
,使文本文件看起來像這樣;
variable_1 = 1;
variable_2 = 22;
variable_3 = 33;
variable_4 = 4;
如何使用 python v3.8 做到這一點?
urls = open('variables.txt', 'r')
lines = urls.readlines() # read all the lines of txt
urls.close()
for index, line in enumerate(lines): # iterate over each line
if index == 1:
line_split = line.split(';')
line = line_split[0] + '2;\n'
if index == 2:
line_split = line.split(';')
line = line_split[0] + '3;\n'
lines[index] = line
with open('variables.txt', 'w') as urls:
urls.writelines(lines) # save all the lines
請在代碼中作為注釋查看我的解釋。
輸入文件(input_file.txt):
variable_1 = 1;
variable_2 = 2;
variable_3 = 3;
variable_4 = 4;
代碼:
# Open the input and output file in context manager. You can be sure the files will be closed!
with open("input_file.txt", "r") as input_file, open("result.txt", "w") as output_file:
for line in input_file: # Iterate on the lines of input file
splited_line = line.split(" ") # Split the lines on space
if "2;" in splited_line[-1]: # If the last element of list is "2;"
splited_line[-1] = "22;\n" # Chane the last element to "22;\n"
elif "3;" in splited_line[-1]: # If the last element of list is "3;"
splited_line[-1] = "33;\n" # Chane the last element to "33;\n"
# Join the elements of list with space delimiter and write to the output file.
output_file.write(" ".join(splited_line))
Output 文件(result.txt):
variable_1 = 1;
variable_2 = 22;
variable_3 = 33;
variable_4 = 4;
更緊湊的代碼:
with open("input_file.txt", "r") as input_file, open("result.txt", "w") as output_file:
for line in input_file:
splited_line = line.split(" ")
splited_line[-1] = "22;\n" if "2;" in splited_line[-1] else splited_line[-1]
splited_line[-1] = "33;\n" if "3;" in splited_line[-1] else splited_line[-1]
output_file.write(" ".join(splited_line))
我的回答建立在丹尼斯的回答之上。
假設data.txt
有以下內容;
variable_1 = 1;
variable_2 = 22;
variable_3 = 33;
variable_4 = 4;
下面的代碼將解決問題。
def write_var_to_file(config_file: str, variable_name: str, variable_content: str) -> None:
from typing import TextIO, List
urls: TextIO = open(config_file, 'r')
lines: List[AnyStr] = urls.readlines() # read all the lines of txt
urls.close()
for index, line in enumerate(lines): # iterate over each line
line_split: List[str] = line.split('=')
var_name: str = line_split[0].strip() # use strip() to remove empty space
if var_name == variable_name:
var_value: str = variable_content + ";\n"
line: str = F"{var_name} = {var_value}"
lines[index] = line
with open(config_file, 'w') as urls:
urls.writelines(lines) # save all the lines
return
write_var_to_file(config_file="data.txt", variable_name="variable_2", variable_content="22")
write_var_to_file(config_file="data.txt", variable_name="variable_3", variable_content="33")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.