1

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 Answers3

2

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)
costaparas
  • 5,047
  • 11
  • 16
  • 26
2

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'))
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
1

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()]
U13-Forward
  • 69,221
  • 14
  • 89
  • 114