Reading one integer at a time using python

How can I read int from file? I have a large (512 MB) txt file that contains integer data like:

0 0 0 10 5 0 0 140
0 20 6 0 9 5 0 0

Now, if I use c = file.read(1), I get only one character at a time, but I need one integer at a time. How:

c = 0
c = 10
c = 5
c = 140 and so on...

Any big heart, please help. Thanks in advance.

+5
source share
3 answers

Here is one way:

with open('in.txt', 'r') as f:
  for line in f:
    for s in line.split(' '):
      num = int(s)
      print num

By performing for line in f, you read bit by bit (using neither read() all, nor readlines). Important because your file is large.

Then you break each line into spaces and read each number as you go.

You can make more mistakes than this simple example, which will be barf if the file contains corrupted data.

, - , , , - , .

+5

512 . , :

my_int_list = [int(v) for v in open('myfile.txt').read().split()]

, , :

def my_ints(fname):
    for line in open(fname):
        for val in line.split():
            yield int(val)

:

for c in my_ints('myfile.txt'):
    # do something with c (which is the next int)
+2

I would do it like this:

  • buffer = file.read (8192)
  • contents + = buffer
  • separate the output line with a space
  • remove the last element from the array (may not be a full number)
  • replace contents with last line of element
  • repeat until buffer becomes None
-1
source

All Articles