Vinay Chandra
Vinay Chandra

Reputation: 532

File Reading problems in Python

While Reading the files in python using f = open ("filename.txt") and accessing the data with f.read(1) and finally finding the position of stream usibg f.tell() for every step; We get a continous numbering starting from 0 to the current position.

The problem i am facing is that i am actually getting a random number as f.tell() for some positions and then continung the numbers. For examle, the f.tell() outputs look something ike the following

0
1
2
3
133454568679978
6
7
8...

Any idea why this is happening?

My Code :

f=open("temp_mcompress.cpp")
current = ' '
   while current != '' :
   print(f.tell())
   current = f.read(1)

f.close()

Temp_mcompress.cpp file :

#include <iostream>

int main(int a)
{
}

OUtput : 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 18446744073709551636 18446744073709551638 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 18446744073709551655 40 41 43 44

Upvotes: 2

Views: 1198

Answers (1)

Bartlomiej Lewandowski
Bartlomiej Lewandowski

Reputation: 11170

It seems I might have found the problem which may still be applicable to python 3.x: source: http://docs.python.org/2.4/lib/bltin-file-objects.html

tell()

Return the file's current position, like stdio's ftell().

Note: On Windows, tell() can return illegal values (after an fgets()) when reading files with Unix-style line-endings. Use binary mode ('rb') to circumvent this problem.

Upvotes: 2

Related Questions