How do I take in multiple variables in a file python file read

Viewed 85

Lets say I have data.txt, and this is inside

0
0
0

How do I get the data from this in one single line? I tried something like

file_in = open('data.txt', 'w+')
a, b, c = file_in.read().split()

but it didn't work so well. How do I correctly get a, b, and c to each get values of 0, from the data.txt file?

3 Answers

Well, first of all, your file opening is clearing the file. You want to open the file for reading -- use the r mode.

To do the unpacking, you can use the splitlines() method.

For example:

file_in = open('data.txt', 'r')
a, b, c = file_in.read().splitlines()
print(a, b, c)

If you just have numbers, and know exactly how many, and you actually want int objects, all you need is:

a, b, c = map(int, open('data.txt'))

Try using splitlines:

file_in = open('data.txt', 'w+')
a, b, c = file_in.read().splitlines()

If you want to convert them to integers, try adding a list comprehension:

file_in = open('data.txt', 'w+')
a, b, c = [int(i) for i in file_in.read().splitlines()]

But if there are possibly not integer-like values in the text file, you could try using an if statement:

file_in = open('data.txt', 'w+')
a, b, c = [int(i) if i.isdigit() else i for i in file_in.read().splitlines()]
Related