0

I have a text file for exemple:

1 2 3

4 5 6 7

8 9 

I want to get the output [1, 2, 3], [4, 5, 6, 7], [8, 9].

I tried the following code:

with open('name_file.txt', 'r') as f:
  text=f.readlines()

But I got the following output:

 '1\t2\t3\n',
 '4\t5\t6\t7\n',
 '8\t9\n',
AKX
  • 152,115
  • 15
  • 115
  • 172
  • 1
    Yes - you've read lines that contain tab characters and have line endings. – AKX Aug 01 '22 at 09:51
  • Have a look into the _pandas_ package it is great for reading, analyising and saving tabular data in various formats. – Jacob Aug 01 '22 at 09:54
  • 2
    @Jacob You absolutely don't need Pandas to read a simple file of tab-separated numbers. – AKX Aug 01 '22 at 09:54

2 Answers2

0

If .readlines() shows you

[
  '1\t2\t3\n',
  '4\t5\t6\t7\n',
  '8\t9\n',
]

you're seeing the lines with line endings intact (since the newline character's escape representation is \n), and your numbers are separated by tabs (whose representation is \t).

You might want

my_list = []
with open('name_file.txt', 'r') as f:
    for line in f:
        my_list.append([int(value) for value in line.strip().split()])

which will read the file line-by-line (iterating over a file does that), remove all leading and trailing spaces from each line (strip()), split the line using all remaining whitespace (so this will work for both tabs and spaces or a combination thereof), and finally use int() to convert the strings to integers.

AKX
  • 152,115
  • 15
  • 115
  • 172
0

Say you have a file called data.txt with the following contents:

1   2   3
4   5   6   7
8   9

You could use a list comprehension to parse each line along with str.split:

data = []
with open('data.txt') as data_file:
    for line in data_file:
        data.append([int(x) for x in line.split()])
print(data)

Output:

[[1, 2, 3], [4, 5, 6, 7], [8, 9]]
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40