Neeraj
Neeraj

Reputation: 201

size of a python file object and seek()

I created a file with the following entry, returned by file.read()

'abcd\nefgh\n1234\nijkl\n5678\n\nend'

I open the file to read now, with 'f' as handler. f.read() returns the above. f.tell() returns 35L sys.getsizeof(f) returns 76. Trying to call f.seek(offset) with offset any higher than 35 returns nothing.

Python documentation says file.seek() moves in bytes. so is there a mismatch between what is returned by sys.getsizeof() and f.tell()/seek() ?

Upvotes: 1

Views: 2994

Answers (3)

Andrew
Andrew

Reputation: 2568

# size of the file in bytes
size = os.path.getsize(pathname)
# another way
f = file(pathname)
size = os.fstat(f.fileno()).st_size

References

Upvotes: 4

Boaz Yaniv
Boaz Yaniv

Reputation: 6424

sys.getsizeof() does not return the size of the file on disk. Instead, it returns the size that the file object (the interface to the real file on disk) takes up in memory.

You could even use sys.getsizeof() with objects that don't have any disk presence. For instacen, if s = 'abcd', then calling sys.getsizeof(s) might return (depending on your implementation) 25, even though s is a string, and it doesn't any space on disk.

Upvotes: 3

Cat Plus Plus
Cat Plus Plus

Reputation: 129914

sys.getsizeof returns a size of an object (i.e. how many bytes a file class instance takes up in the memory), and has nothing to do with the size of the file contents.

Upvotes: 7

Related Questions