How to make a text file into a list of arrays (an array in an array) and remove spaces / newlines

For example, I have a txt file:

3 2 7 4
1 8 9 3
6 5 4 1
1 0 8 7

There are 4 numbers on each line, and there are 4 lines. At the end of the lines there is \ n (except for the last). The code I have is:

f = input("Insert file name: ")
file = open(f, encoding="UTF-8")

I want the text file to become [[3,2,7,4],[1,8,9,3],[6,5,4,1],[1,0,8,7]].

I tried everything, I know that the answer is probably very simple, but I just give up after an hour of trying. Tried read(), readlines(), split(), splitlines(), strip()and all I could find on the Internet. So much can not even make a difference between the two ...

+4
source share
3 answers

, , , split, :

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]
  • listcomp ( )
  • listcomp

, , - , .

( , file python 2, python 3, )

+4

,

[map(int,i.split()) for i in filter(None,open('abc.txt').read().split('\n'))]

In [75]: print open('abc.txt').read()
3 2 7 4

1 8 9 3

6 5 4 1

1 0 8 7

split .

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', '']

.

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

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']]

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]]
+2

. , , map , int integer , this , , .

, - .

f = input("File name? ")
with open(f, encoding="UTF-8") as file:
    data = [list(map(int, line.split())) for line in file]
print(data)  # -> [[3, 2, 7, 4], [1, 8, 9, 3], [6, 5, 4, 1], [1, 0, 8, 7]]
+2

Source: https://habr.com/ru/post/1674876/


All Articles