这是一种方法:
with open(filename, "r") as f: # opens the file `filename` and allows it to be referenced with the name `f`
counter = 0 # initializes the counter of the character as 0
for line in f: # (you can iterate directly over files)
if character in line:
print(line)
counter += line.count(character)
最好使用with
语句打开文件,因为这意味着无论发生什么情况都会关闭它(例如,即使在管理文件时发生异常)。
据我了解,您的代码与该问题似乎没有多大意义,但这似乎最像您想要的:
def countLetterString(char, string):
if string == "":
return None # explicit to be clear
else:
return string.count(char)
with open(filename, "r") as f:
counter = 0
for line in f:
count = countLetterString(the_character, line)
if count:
print(line)
counter += count
如果你正在寻找一个递归解决方案(你可能不是):
def count_and_print(file_object, character):
def do_line(file, counter):
line = file.readline()
if line:
if character in line:
print(line)
return do_line(file, counter + line.count(character))
else:
return counter
return do_line(file_object, 0)