12

I have a file format like this:

9 8 1
3 4 1
...
...

Now, I want to get each line as three integers.

When I used

for line in f.readlines():
    print line.split(" ")

The script printed this:

['9', '8', '1\r\n']
['3', '4', '1\r\n']
...
...

How can I get each line as three integers?

aradhak
  • 836
  • 1
  • 9
  • 22
sezina
  • 482
  • 2
  • 5
  • 18
  • 1
    Do you mean `for line in f.readlines():` – wim Jul 06 '12 at 01:28
  • Don't cast. Convert. The more general question for that is: "How to covert '123' to the corresponding number 123?" –  Jul 06 '12 at 01:32

5 Answers5

18

Using the code you have and addressing your specific question of how to convert your list to integers:

You can iterate through each line and convert the strings to int with the following example using list comprehension:

Given:

line =['3', '4', '1\r\n']

then:

int_list = [int(i) for i in line]

will yield a list of integers

[3, 4, 1]

that you can then access via subscripts (0 to 2). e.g.

int_list[0] contains 3,

int_list[1] contains 4,

etc.


A more streamlined version for your consideration:

with open('data.txt') as f:
    for line in f:
        int_list = [int(i) for i in line.split()]
        print int_list

The advantage of using with is that it will automatically close your file for you when you are done, or if you encounter an exception.

UPDATE:

Based on your comments below, if you want the numbers in 3 different variables, say a, b and c, you can do the following:

   for line in f:
       a, b, c = [int(i) for i in line.split()]
       print 'a = %d, b = %d, c = %d\n' %(a, b, c)

and get this:

    a = 9, b = 8, c = 1

This counts on there being 3 numbers on each line.

Aside:

Note that in place of "list comprehension" (LC) you can also use a "generator expression" (GE) of this form:

    a, b, c = (int(i) for i in line.split())

for your particular problem with 3 integers this doesn't make much difference, but I show it for completeness. For larger problems, LC requires more memory as it generates a complete list in memory at once, while GE generate a value one by one as needed. This SO question Generator Expressions vs. List Comprehension will give you more information if you are curious.

Community
  • 1
  • 1
Levon
  • 138,105
  • 33
  • 200
  • 191
  • Actually, I haven't enough reputation to vote. Vote up requires at least 15 reputation. If I want to use the data to build a graph datastructure, format them as a list is a bad choice. Is there some easy way to format them just as three single integer? – sezina Jul 06 '12 at 01:12
  • 1
    @sezina you don't need any points to accept an answer. It's the little check-mark on the side of this answer. – Trufa Jul 06 '12 at 01:23
  • @Levon: It does't work. I got a `ValurError: need more then 2 values to unpack`. – sezina Jul 06 '12 at 01:27
  • @sezina Check your data file, make sure it only contains 3 numbers per line and there are no blank lines (at the end of the file either). I tested this code with a file before I posted it, so it works. This message comes when you *have fewer* than 3 items on a line. In this case you must have only **2** items on a line. – Levon Jul 06 '12 at 01:29
  • @Levon: Aha. I solved the problem. Thanks a lot. And I have accepted. – sezina Jul 06 '12 at 01:36
  • @sezina Did you have only 2 values on a line? Just curious. Happy to help. – Levon Jul 06 '12 at 01:37
4
with open("myfile.txt") as f:
    for line in f:
        int_list = [int(x) for x in line.split()]

You don't say what you want to do with the list of integers, there may be a better way to iterate over them, depending.

If you "need the values as three different variables," then"

a, b, c = int_list

though you could also use:

int_list[0]
int_list[1]
int_list[2]

as desired.

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
1
line.strip().split(" ") 

would do.

more complete, with all lines still intact in one large string:

data = f.read().strip()    # loose final \n
[ int(x.split(" ")) for x in data.split('\n')]

would give you a list with answers you want for each line.

Andre Blum
  • 391
  • 3
  • 6
0

This block of code should solve your problem:

f = open(filepath)
for line in f:
    intList = map(int, line.strip().split())
    print intList
f.close()
octopusgrabbus
  • 10,555
  • 15
  • 68
  • 131
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
0

If you wanna store the integers in three variables :

with open('data1.txt') as f:
    for line in f:
        a,b,c=(int(x) for x in line.split()) 
        print a,b,c 

output:

9 8 1
3 4 1
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504