在Python中,可以使用以下方法来统计并输出文件的行数:
方法1:使用readlines()
方法逐行读取文件内容,并利用len()
函数统计行数。
def count_lines(filename):
with open(filename, 'r') as file:
lines = file.readlines()
line_count = len(lines)
return line_count
filename = 'example.txt'
line_count = count_lines(filename)
print("文件", filename, "共有", line_count, "行。")
方法2:使用enumerate()
函数遍历文件的每一行,并利用计数器统计行数。
def count_lines(filename):
with open(filename, 'r') as file:
line_count = 0
for line in file:
line_count += 1
return line_count
filename = 'example.txt'
line_count = count_lines(filename)
print("文件", filename, "共有", line_count, "行。")
无论使用哪种方法,都需要注意文件路径是否正确,并确保文件存在和可读取。