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?
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?
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]]
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 = ',')