Jason Rome
Jason Rome

Reputation: 29

Reading data from a file in Python

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?

Upvotes: 1

Views: 134

Answers (4)

Konstantin
Konstantin

Reputation: 2659

I would use numpy.loadtxt() for that:

import numpy
numpy.loadtxt("yourFileName.txt", dtype=int, delimiter=",")

Upvotes: 0

Óscar López
Óscar López

Reputation: 236150

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.

Upvotes: 3

Graeme Stuart
Graeme Stuart

Reputation: 6063

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

Upvotes: 4

Thomas Orozco
Thomas Orozco

Reputation: 55303

You might do:

map(int, line.strip().split(','))

Here's what this does

  1. line.strip() converts "1,100\n" to "1,100"
  2. line.split(',') converts"1,100"to("1", "100")`
  3. map(int, ...) applies int to each argument, and returns (1, 100)

Upvotes: 2

Related Questions