For example I have a txt file:
3 2 7 4
1 8 9 3
6 5 4 1
1 0 8 7
On every line there are 4 numbers and there are 4 lines. At end of lines there's \n (except the last one). The code I have is:
f = input("Insert file name: ")
file = open(f, encoding="UTF-8")
What I want is the text file to become [[3,2,7,4],[1,8,9,3],[6,5,4,1],[1,0,8,7]]
.
I have tried everything, I know the answer is probably really simple, but I just really give up after an hour of attempts. Tried read()
, readlines()
, split()
, splitlines()
, strip()
and whatever else I could find on the internet. So many can't even make a difference between them...
Once you opened the file, use this one-liner using split
as you mentionned and nested list comprehension:
with open(f, encoding="UTF-8") as file: # safer way to open the file (and close it automatically on block exit)
result = [[int(x) for x in l.split()] for l in file]
note that it will fail if there are something else than integers in your file.
(as a side note, file
is a built-in in python 2, but not anymore in python 3, however I usually refrain from using it)
You can do like this,
[map(int,i.split()) for i in filter(None,open('abc.txt').read().split('\n'))]
Line by line execution for more information
In [75]: print open('abc.txt').read()
3 2 7 4
1 8 9 3
6 5 4 1
1 0 8 7
split
with newline.
In [76]: print open('abc.txt').read().split('\n')
['3 2 7 4', '', '1 8 9 3', '', '6 5 4 1', '', '1 0 8 7', '']
Remove the unnecessary null string.
In [77]: print filter(None,open('abc.txt').read().split('\n'))
['3 2 7 4', '1 8 9 3', '6 5 4 1', '1 0 8 7']
split
with spaces
In [78]: print [i.split() for i in filter(None,open('abc.txt').read().split('\n'))]
[['3', '2', '7', '4'], ['1', '8', '9', '3'], ['6', '5', '4', '1'], ['1', '0', '8', '7']]
convert the element to int
In [79]: print [map(int,i.split()) for i in filter(None,open('abc.txt').read().split('\n'))]
[[3, 2, 7, 4], [1, 8, 9, 3], [6, 5, 4, 1], [1, 0, 8, 7]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With