1

numbers.txt:

5      6
3      8
9      10

I want to create a list from a numbers.txt, my list should be [[5,6],[3,8],[9,10]

But I keep getting \t(between numbers) and \n(at the end, ex. 10\n etc.) in the output. How can I fix that? I should be getting [[5,6], [3,8], [9,10]]

My code is:

file=open("numbers.txt","r")
l=[]
for line in file:
    l.append(line.split(','))

print(l)

thanks(note: tab is used between two numbers in every line)

Anton vBR
  • 18,287
  • 5
  • 40
  • 46
mesboomin
  • 35
  • 5

4 Answers4

2

Looks like you got tab \t separated values. This is my fav:

with open('numbers.txt') as f:
    # split the file by rows and rows by separator
    l = [i.split('\t') for i in f.read().split('\n')]

print(l) # [['5', '6'], ['3', '8'], ['9', '10']]

With open... makes sure that the file is closed after.


Other alternatives would include importing libraries. Numpy and pandas are the two leading packages to deal with arrays/data/tables/matrixes. Both of them will evaluate your input (and in this case it would be stored as integers). Numpy was suggested by Joran Beasley.

import numpy as np
l = np.genfromtxt('numbers.txt').tolist()

import pandas as pd
l = pd.read_csv('numbers.txt', sep='\t', header=None).values.tolist()

If you need it to be integers or float, change code below to one of these:

l = [list(map(int,i.split('\t'))) for i in f.read().split('\n')]
# [[5, 6], [3, 8], [9, 10]]
l = [list(map(float,i.split('\t'))) for i in f.read().split('\n')]
# [[5.0, 6.0], [3.0, 8.0], [9.0, 10.0]]
Anton vBR
  • 18,287
  • 5
  • 40
  • 46
0

I would use:

l.append(','.join(line.split()))

split without arguments will split your line by whitespaces, include tab or newline characters.

dvnguyen
  • 2,954
  • 17
  • 24
0
dat = numpy.genfromtxt("numbers.txt")

Is probably how i would do it ...

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
0

You can try this :

print(list(map(lambda x:x.split(),open('file.txt','r'))))

output:

[['5', '6'], ['3', '8'], ['9', '10']]

P.S: you can read this too if you have doubt what happend if you don't close the file.

Aaditya Ura
  • 12,007
  • 7
  • 50
  • 88