Skip to main content
 首页 » 编程设计

python之len 函数如何实际用于文件

2025年05月04日10kenshinobiy

python 文档说:返回对象的长度(项目数)。参数可以是序列(字符串、元组或列表)或映射(字典)。

代码:

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) 

文件内容: 一二三

运行这个简单程序后,我得到输出:输入文件长 14 个字节

问题:

我不明白,如果我的文件只写了 11 个字符(一二三)怎么能 len 返回 14 个字节而不是简单的 11 个字节?(顺便说一句,这些字节有什么用?)在 python 中解释器如果我输入 s = "一二三"然后 len(s) 我得到 13,所以我很困惑。

请您参考如下方法:

“一二三”确实是 13 个字符(11 个字母 + 2 个空格)。

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

很可能你在末尾有一个额外的字符,这解释了 14。