0101amt
0101amt

Reputation: 2478

How does len function actually work for files?

The python docs say: Return the length (the number of items) of an object. The argument may be a sequence (string, tuple or list) or a mapping (dictionary).

Code:

from sys import argv

script, from_file = argv

input = open(from_file)
indata = input.read()

print "The input file is %d bytes long" % len(indata)

Contents of the file: One two three

Upon running this simple program I get as output: The input file is 14 bytes long

Qutestion:

I don't understand, if my file has written in it only 11 characters(One two three) how can len return me 14 bytes and not just simply 11?(what's with the bytes by the way?) In the python interpreter if I type s = "One two three" and then len(s) I get 13, so I am very confused.

Upvotes: 1

Views: 1557

Answers (3)

Aleksandr Kravets
Aleksandr Kravets

Reputation: 5947

I used your code and created file similar to your by content. Result of running: indeed you have extra non-printable character in your "One two three" file. It's the only explanation. Space and line break - most obvious things to look up for.

Upvotes: 1

RanRag
RanRag

Reputation: 49567

One two three

one = 3 characters

two = 3 characters

three = 5 characters

and than you have two spaces. So a total of 13 characters.

when reading from file there is an extra space in your file so 14 characters.

In your python interpreter do this:

st = " "
len(st)

output = 1

Upvotes: 2

Savino Sguera
Savino Sguera

Reputation: 3572

"One two three" is indeed 13 chars (11 letters + 2 spaces).

>>> open("file.txt", 'w').write("one two three")
>>> len(open("file.txt").read())
13

Most likely you have an extra char for the endline, which explains the 14.

Upvotes: 7

Related Questions