【发布时间】:2016-07-29 18:52:53
【问题描述】:
您好,我是编程初学者。我正在阅读 Zed Shaw 的书 Learn Python the Hard Way,遇到了一个我觉得奇怪的错误。我想知道为什么它一直给我错误:TypeError:我在 Windows Powershell 中运行我的代码后,'file' 类型的对象没有 len()。我运行的代码:
from sys import argv
from os.path import exists
script, from_file, to_file = argv
print "Copying from %s to %s" % (from_file, to_file)
in_file = open(from_file, "r")
print "The input file is %d bytes long" % len(in_file)
它说错误在最后一行。我不明白为什么会发生此错误,因为如果我是对的,我以读取模式打开文件并将其保存在变量 in_file 中。那么为什么它不能读取 in_file 的 len 呢?他在 Zed Shaw 的书中写道
in_file = open(from_file)
indata = in_file.read()
在我写的地方
in_file = open(from_file, "r")
评论:# we could do these two on one line, how?所以我以为他想让我写我写的代码。
如果有人可以帮助我,将不胜感激。提前致谢
【问题讨论】:
-
“所以我以为他想让我写我写的代码。” - 不。您似乎误解了
"r"的含义。 -
以读取模式打开文件与读取文件有很大不同。这是为了阅读而打开一本书(而不是突出显示或下划线)与实际阅读之间的区别。