在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, "行。")
無論使用哪種方法,都需要注意文件路徑是否正確,并確保文件存在和可讀取。