Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a text file into a list of arrays (array-in-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

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...

like image 780
Never Ever Avatar asked Feb 05 '23 16:02

Never Ever


2 Answers

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]
  • the inner listcomp splits & converts each line to integers (making an array of integers)
  • the outer listcomp just iterates on the lines of the 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)

like image 194
Jean-François Fabre Avatar answered Feb 07 '23 17:02

Jean-François Fabre


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]]
like image 22
Rahul K P Avatar answered Feb 07 '23 19:02

Rahul K P