gpt4 book ai didi

python - 使用python修改文本文件中的变量值

转载 作者:行者123 更新时间:2023-12-02 02:24:51 25 4
gpt4 key购买 nike

我有一个包含以下内容的文本文件;

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

关于python - 使用python修改文本文件中的变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65850246/

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