Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
79 views
in Technique[技术] by (71.8m points)

Modify variable value in text file with python

I have a text file with the following content;

variable_1 = 1;
variable_2 = 2;
variable_3 = 3;
variable_4 = 4;

Using python, I would like to modify variable_2 to 22 and variable_3 to 33 such that the text file will look like this;

variable_1 = 1;
variable_2 = 22;
variable_3 = 33;
variable_4 = 4;

How can this be done using python v3.8?

question from:https://stackoverflow.com/questions/65850246/modify-variable-value-in-text-file-with-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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;
'
    if index == 2:
        line_split = line.split(';')
        line = line_split[0] + '3;
'
    lines[index] = line

with open('variables.txt', 'w') as urls:
    urls.writelines(lines)  # save all the lines

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...