Tom
Tom

Reputation: 43

How can I import a string file into a list of lists?

Basically I have a text file:

-1  2  0  
 0  0  0  
 0  2 -1  
-1 -2  0   
 0 -2  2   
 0  1  0   

Which I want to be put into a list of lists so it looks like:

[[-1,2,0],[0,0,0],[0,2,-1],[-1,-2,0],[0,-2,2],[0,1,0]]

I have this code so far but it produces a list of strings within lists.

import os  
f = open(os.path.expanduser("~/Desktop/example board.txt"))  
for line in f:  
    for i in line:  
        line = line.strip()  
        line = line.replace(' ',',')  
        line = line.replace(',,',',')  
        print(i)
        print(line)  
    b.append([line])  

That produces [['-1,2,0'],['0,0,0'],['0,2,-1'],['-1,-2,0'],['0,-2,2'],['0,1,0']] Which is almost what I want except with the quotation marks.

Upvotes: 4

Views: 172

Answers (5)

Jordonias
Jordonias

Reputation: 5848

Simple solution with no additional libraries

import os

lines = []
f = open(os.path.expanduser("~/Desktop/example board.txt"))
for line in f:
    x = [int(s) for s in line.split()]
    lines.append(x)

Output:

[[-1, 2, 0], [0, 0, 0], [0, 2, -1], [-1, -2, 0], [0, -2, 2], [0, 1, 0]]

Upvotes: 0

Burhan Khalid
Burhan Khalid

Reputation: 174624

Use the csv module:

import csv

with open(r'example board.txt') as f:
    reader = csv.reader(f, delimiter='\t')
    lines = list(reader)

print lines

Upvotes: 2

pcurry
pcurry

Reputation: 1414

If you have comma separated values, the csv module is frequently your best bet. If that's not a good fit, for whatever reason, then here's a way to go about it with just the string and list built-ins.

You could do the whole thing in a list comprehension:

with open('~/Desktop/example board.txt', 'r') as fin:
    lines = [[int(column.strip()) for column in row.split(',')] for row in fin]

But that's opaque and could stand to be refactored:

def split_fields(row):
    fields = row.split(',')
    return [int(field.strip()) for field in fields]       

with open('~/Desktop/example board.txt', 'r') as fin:
    lines = [split_fields(row) for row in fin]

Upvotes: 0

wim
wim

Reputation: 362557

I would recommend just using numpy for this rather than reinvent the wheel...

>>> import numpy as np
>>> np.loadtxt('example board.txt', dtype=int).tolist()
[[-1, 2, 0], [0, 0, 0], [0, 2, -1], [-1, -2, 0], [0, -2, 2], [0, 1, 0]]

Note: depending on your needs, you may well find a numpy array to be a more useful data structure than a list of lists.

Upvotes: 4

Jarie Bolander
Jarie Bolander

Reputation: 384

This should do the trick since it appears that you want the data to be numbers and not strings:

fin = open('example.txt','r')
# The list we want
list_list = []
for line in fin:
    # Split the numbers that are separated by a space. Remove the CR+LF.
    numbers = line.replace("\n","").split(" ")
    # The first list
    list1 = []
    for digit in numbers:
        list1.append(int(digit))

    # The list within the list
    list_list.append(list1)

fin.close()

This produces an output like so:

[[-1, 2, 0], [0, 0, 0], [0, 2, -1], [-1, -2, 0], [0, -2, 2], [0, 1, 0]]

Upvotes: 1

Related Questions