I have a data file that looks like this:
1,100
2,200
3,-400
4,500
As you can see, each data point has 2 components When I do file.readlines() they all come up as strings such as '1,100\n' so I am wondering how would I make them into integers?
This is comma separated data so using the csv module is a good approach.
Simple version to extract the string data
import csv
with open('data.csv', 'r') as f:
reader = csv.reader(f)
for a, b in reader:
print a, b
or with Thomas's approach to cast data to integers
import csv
with open('data.csv', 'r') as f:
reader = csv.reader(f)
for line in reader:
a, b = map(int, line)
print a, b
csv module will save you a lot of pain as you begin to deal with more complicated data loading problems.Read line by line and then split each line:
with open('file.txt', 'r') as f:
for line in f:
a, b = [int(x) for x in line.split(',')]
# here you can use a and b as numbers
The above has the advantage of using the with statement, which takes care of automatically closing the file even in the event of an error.
You might do:
map(int, line.strip().split(','))
Here's what this does
line.strip() converts "1,100\n" to "1,100"line.split(',') converts"1,100"to("1", "100")`map(int, ...) applies int to each argument, and returns (1, 100)strip. int function ignores newline characters for you. Good answer though so +1.I would use numpy.loadtxt() for that:
import numpy
numpy.loadtxt("yourFileName.txt", dtype=int, delimiter=",")