1

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?

4 Answers 4

4

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
Sign up to request clarification or add additional context in comments.

1 Comment

While this looks like unnecessary overhead, the csv module will save you a lot of pain as you begin to deal with more complicated data loading problems.
3

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.

Comments

2

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)

1 Comment

Not necessary to strip. int function ignores newline characters for you. Good answer though so +1.
0

I would use numpy.loadtxt() for that:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.