I'm not exactly new to Python, but I do still have trouble understanding what makes something "Pythonic" (and the converse).
So forgive me if this is a stupid question, but why can't I get the size of a file by doing a len(file)?
file.__len__
is not even implemented, so it's not like it's needed for something else? Would it be confusing/inconsistent for some reason if it was implemented to return the file size?
The python os module has stat() function where we can pass the file name as argument. This function returns a tuple structure that contains the file information. We can then get its st_size property to get the file size in bytes.
The len() function returns the length of a string, the number of chars in it. It is valid to have a string of zero characters, written just as '' , called the "empty string". The length of the empty string is 0.
file is an iterator. To find the number of lines you need to read the entire file
sum(1 for line in file)
if you want the number of bytes in a file, use os.stat
eg
import os os.stat(filename).st_size
Files have a broader definition, especially in Unix, than you may be thinking. What is the length of a printer, for example? Or a CDROM drive? Both are files in /dev, and sort of in Windows.
For what we normally think of as a file, what would its length be? The size of the variable? The size of the file in bytes? The latter makes more sense, but then it gets ickier. Should the size of the file's contents be listed, or its size on disk (modulus allocation unit size). The question arises again for sparse files (files that have large empty sections which take no space, but are part of the file's normally reported size, supported by some file systems like NTFS and XFS).
Of course, the answer to all of those could be, "just pick one and document what you picked." Perhaps that is exactly what should be done, but to be Pythonic, something usually must be clear-cut without having to read a lot of docs. len(string)
is mostly obvious (one may ask if bytes or characters are the return value), len(array)
is obvious, len(file)
maybe not quite enough.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With