Skip to main content
 首页 » 编程设计

python之使用 with open,我得到文件对象,因为没有属性计数

2025年05月04日22小虾米

我写了下面的代码,我觉得没问题,但是当我运行它的时候,我得到了一个错误:

#!/usr/bin/env python2.7 
 
with open("helloworld.txt", "r") as fcontent: 
    lc = 0 
    for eachline in fcontent: 
        lc += 1 
        if fcontent.count(eachline) > 1: 
            print(lc,eachline) 

我得到的错误:

Traceback (most recent call last): 
  File "./openfile.py", line 7, in <module> 
    if fcontent.count(eachline) > 1: 
AttributeError: 'file' object has no attribute 'count' 
 

我做错了什么?我觉得它很小,但我似乎无法弄清楚。我怀疑是因为我正在使用 with open。当我不使用 with 扫描文件时,我没有收到任何错误:

#!/usr/bin/env python2.7 
 
from sys import exit 
 
filec = open("hellowDup.txt", "r") 
fcontent = filec.readlines() 
lc = 0 
for eachline in fcontent: 
    lc += 1 
    if fcontent.count(eachline) > 1: 
        print(lc,eachline) 
exit(0) 
 

请您参考如下方法:

.count() 是list 对象的方法。

list.count(x)

Return the number of times x appears in the list.

(Source: https://docs.python.org/3/tutorial/datastructures.html#more-on-lists)

它不是file 对象的方法。所以你不能在那里使用它。在您的第二个示例中,您正在使用 file 对象的 .readlines() 方法读取文件:

readlines(hint=-1)

Read and return a list of lines from the stream. hint can be specified to control the number of lines read: no more lines will be read if the total size (in bytes/characters) of all lines so far exceeds hint.

(Source: https://docs.python.org/3/library/io.html#io.IOBase.readlines)

因为 .readlines() 方法返回一个 list,你可以在那里调用你的 .count() 方法。