1

I am new to Python. My file contains these numbers:

2,3
4,5
7,8
-4,3

How can I read this file and convert it into a two dimensional list so that I can calculate an area?

Mischa
  • 42,876
  • 8
  • 99
  • 111
sweetypie
  • 11
  • 2

2 Answers2

3

something like this:

>>> with open("data1.txt") as f:
...    lis=[list(map(int,x.split(","))) for x in f]
...    print lis
... 
[[2, 3], [4, 5], [7, 8], [-4, 3]]
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
1

Instead of manually parsing the file, you could also use the csv module to do this. A small example:

import csv
with open('data1.txt', 'rb') as csvfile:
  spamreader = csv.reader(csvfile, delimiter=',')

twod_list = [row for row in spamreader]

In addition, if you want to start working with numpy (which you want if you want to do serious calculations), take a look at this SO question for how to read your data into a numpy array. The following code I copied form the linked question:

from numpy import genfromtxt
my_data = genfromtxt('data1.txt', delimiter = ',')
Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149