user1478335
user1478335

Reputation: 1839

return a list of lists from a text file

results = open(filename, 'r')


   line = results.readline()
   while line != '':
    # results for a single draw
    star = line[line.rfind('\t') :]
    stars.append(star)
    line =results.readline()
'''

while line != '':


   main = [line[:line.rfind('\t')]]
   mains.append(main)
   line =results.readline()
return (mains)

I am using the above script to read from a text file in the format 1,2,3,4,5 tab 9,10new line 6,7,8,9,10 tab 11,12 and am trying to get back [[1,2,3,4,5],[6,7,8,9,10]]The above script gives me [['1,2,3,4,5'],['6,7,8,9,10']] -the parentheses prevent me using the data. Forgive me for once again being stupid, but how do I get the list format back from the text file? I did try to read other posts, but haven't been able to apply the suggestions - too new to this Many thanks for any help

Upvotes: 0

Views: 198

Answers (2)

moon.musick
moon.musick

Reputation: 5664

Try:

# say your data is in file named 'testfile'
$ cat testfile 
1,2,3,4,5   9,10
6,7,8,9,10  11,12

# the actual code
datafile = [line.strip().split('\t')[0].split(',') for line in open('testfile')]   
result = []
for l in datafile:
    result.append([int(string) for string in l])
# test the results
print(result)
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]

EDIT: For getting both parts of each line, try:

datafile = [line.strip() for line in open('testfile')]
datafile = [line.split('\t') for line in datafile if line]
datalist = list(zip(*datafile))
result = []
for index in datalist:
    for i in index:
        result.append([int(string) for string in i.split(',')])
# you can access the result list by indexing:
print(result[:2], result[2:])
# or assign to new lists:
firstlist, secondlist = result[:2], result[2:]
print(firstlist, secondlist)

Upvotes: 0

Muhammad Towfique Imam
Muhammad Towfique Imam

Reputation: 1343

Try this:

results = open(filename, 'r')
line = results.readline()
mains = []
while line != '':
  stars = line[:line.rfind('\t')].split(',')
  nums = [int(n) for n in stars]
  mains.append(nums)
  line =results.readline()

Upvotes: 3

Related Questions