简体   繁体   中英

How to update a variable in python 3.6 to that of a string of text in a .txt file

Say I want to update 3 variables.

X_Variable_1 X_Variable_2 X_Variable_3

(No these aren't the real names of the variables, but just for example)

Here is the text file's contents

Test Test True

I want X_Variable_1 to be updated to the 1st line of text, overwriting anything else on there, X_Variable_2 happening a similar way, except the second line of text in the file, and then X_Variable_3 being updated to the 3rd line of text

So in this manner, it should update them to

X_Variable_1 = ('Test')
X_Variable_2 = ('Test')
X_Variable_3 = (True)

Thanks

Try this:

#!/usr/bin/python
X_Variable_1, X_Variable_2, X_Variable_3 = open("FILENAME").readlines()

Or if you want the variables not to have '\\n' chars at the end, do this:

#!/usr/bin/python
X_Variable_1, X_Variable_2, X_Variable_3 = [line.rstrip() for line in open("FILENAME").readlines()]

If you have more lines than 3, you can discard all additional lines in the file as well:

#!/usr/bin/python
X_Variable_1, X_Variable_2, X_Variable_3, *_ = [line.rstrip() for line in open("FILENAME").readlines()]

In all examples, set "FILENAME" to the file name you want to read, with or without the path (either relative or absolute).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM