user1504866
user1504866

Reputation: 11

reading in csv lines and creating lists for each line

I have a text file with lines of X,Y coordinates. Like this:

0,23.345,-122.456

1,12.546,-118.987

2,67.435,-104.112

How can I bring these lines into python so each line is their own list when it comes in?

Each of those lines is a pair of coordinates, which equals one point. So I need to then compare line 0 to 1 and line 1 to 2 and so on. Wouldn't I want each of those lines to be a list so that I could access them?

Upvotes: 1

Views: 1285

Answers (3)

Colin Dunklau
Colin Dunklau

Reputation: 3111

This Python template will result in reading each .csv row into a list of lists.

import csv
reader = csv.reader(open('mycsv.csv'))
mylines = list(reader)

Upvotes: 4

aeter
aeter

Reputation: 12700

import csv
with open("csvfile.csv", "rb") as f:
  lines = list(csv.reader(f))

>>> lines
[['0', '23.345', '-122.456'], ['1', '12.546', '-118.987'], ['2', '67.435', '-104.112']]

Upvotes: 2

Bit Monkey
Bit Monkey

Reputation: 21

matrix = []
line = fileHandle.readline()
while (line) :
     currentList = line.strip().split(",")
     matrix.append(currentList)
     line = fileHandle.readline()

This will end with a list of lists where each internal list is a list of the different elements of the line. The line of the group will be the index in the matrix (0 based).

Upvotes: 0

Related Questions