我一直在研究python教程,遇到了一个我根本无法解决的问题。谷歌没有发现任何具体的东西,几个小时后,很多试验和错误我仍然无法解决。
无论如何,下面的代码是本教程的简化版本。它工作正常并打印出我的文件长度为17个字节:
from sys import argv
from os.path import exists
script, file1 = argv
file_open = open(file1)
file_read = file_open.read()
print "the file is %s bytes long" % len(file_read)
然后教程要求将第6行和第7行合并为一行。如果我这样做它有效:
from sys import argv
from os.path import exists
script, file1 = argv
file_read = open(file1).read()
print "the file is %s bytes long" % len(file_read)
但是,如果我像这样做,那么我收到一条错误消息,上面写着TypeError: object of type 'file' has no len()
:
from sys import argv
from os.path import exists
script, file1 = argv
file_read = open(file1, "r+")
print "the file is %s bytes long" % len(file_read)
我的问题是,当我添加“r +”以确保读取打开的文件时,我无法解决为什么会出现错误消息。 (尽管如此,无论如何读取都是默认的,所以即使添加r +也是不必要的)
任何帮助将不胜感激。非常感谢:))
答案 0 :(得分:3)
我想你忘记了.read()
:
file_read = open(file1, "r+")
所以file_read
是一个文件对象。试试:
file_read = open(file1, "r+").read()
,它将按预期返回一个字符串。
答案 1 :(得分:2)
无论您是以r
模式,r+
模式还是任何其他模式打开它,打开内置open
的文件都会返回file object:
>>> open('test.txt', 'r+')
<open file 'test.txt', mode 'r+' at 0x013D9910>
>>> type(open('test.txt', 'r+'))
<type 'file'>
>>>
此外,您无法在此对象上使用内置len
:
>>> len(open('test.txt', 'r+'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object of type 'file' has no len()
>>>
这是因为从技术上讲,文件对象没有长度。它只是指向某个文件的指针。
正如您所指出的,解决问题的方法是首先调用文件对象的read
方法。这样做会将文件的内容作为字符串返回,然后您可以使用len
:
>>> open('test.txt', 'r+').read()
'hello world'
>>> len(open('test.txt', 'r+').read())
11
>>>
答案 2 :(得分:0)
在第二个示例中,您试图找到文件指针的长度,这是不可能的。添加:
file_read.read()
而不仅仅是file_read
答案 3 :(得分:0)
使用len时,它只接受具有特定type
的对象,如果您传入的对象为<type 'file'>
,则会引发异常。
>>> f = open('/some/file/path', 'r+')
>>> type(f)
<type 'file'>
>>>
>>> type(f.read()) # the read method returns an object with type 'str'
<type 'str'>
此处f.read()
会返回str
个对象。