gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:03:23 24 4
gpt4 key购买 nike

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。

关于python - len 函数如何实际用于文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8864977/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com