Home > Mobile >  How to assign numbers from a file to variables after reading the file in python?
How to assign numbers from a file to variables after reading the file in python?

Time:03-19

For example let's say I have two numbers 2 and 3 in a file (data.txt). How to assign those numbers to two variables say a and b while reading the file?

The data.txt has two numbers 2 and 3 in two separate lines

the code I am using is

file = open("data.txt", "r")
a=file.readlines(1)
b=file.readlines(2)

CodePudding user response:

"readlines" fuction return a list, not string or integer. You need to tell Python to convert that. Here is a simple and clear solution for you:

file = open("data.txt", "r")
a=file.readlines(1)
b=file.readlines(2)
a2 = int(a[0])
b2 = int(b[0])
print(a2)

CodePudding user response:

The other answer works well for 2 lines. But if you want to consider adding more variables in the future, the following approach is much cleaner.

with open("data.txt", "r") as fin:  # with operator automatically call the .close() function
  data = fin.read() # data -> "2\n3"

values = data.split("\n") # values -> [2, 3]
values = [int(x) for x in values] # convert all values to integer

a = values[0] # a -> 2
b = values[1] # b -> 3

If you want to have more variables in the future, you only need to add more lines like below

c = values[2]
  • Related