您好,我是编程的初学者。我正在阅读Zed Shaw的书“学习Python的艰难之路”,我遇到了一个我发现很奇怪的错误。我想知道为什么它一直给我错误:TypeError:类型'文件'的对象在Windows Powershell中运行我的代码后没有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?
所以我以为他想让我写下我写的代码。
如果有人可以帮助我,我将不胜感激。提前致谢
答案 0 :(得分:1)
他希望你这样做file = open("/path/to/file.txt").read()
in_file是对您打开的文件的引用。
如果您想存储文件的内容而不是参考文件的内容,可以按照上述步骤进行操作。
file
在此file
之后会为您提供文件内容,您可以使用len(file)
变量来获取此类内容的长度
{{1}}之后,您将获得文件内容中的符号数
我希望你有意义。
注意强>
这是不好的做法,您需要保留文件参考,并参考进行操作。