这是一项家庭作业,我似乎无法弄明白。
“编写一个程序,要求用户提供文件名。程序应该只显示文件内容的前五行。如果文件包含少于五行,则应显示文件的全部内容。”
每当程序读取超过5行的文件时,它只打印前5行。但是,当用少于5行读取文件时,它应该打印整个文件,但它不会这样做。任何帮助表示赞赏。
def file_head_display():
total = 0
file = str(input('Enter the name of the file'))
f_open = open (file, 'r')
line1 = f_open.readline()
line2 = f_open.readline()
line3 = f_open.readline()
line4 = f_open.readline()
line5 = f_open.readline()
for line in f_open:
amount = int(line)
total += amount
if total > 5:
print(line1)
print(line2)
print(line3)
print(line4)
print(line5)
else:
contents = f_open.read()
print(contents)
file_head_display()
答案 0 :(得分:0)
工作解决方案
def file_head_display(limit = 5):
file = str(input('Enter the name of the file: '))
f_open = open (file, 'r')
line_counter = 0
for line in f_open: # for each line in the text file
if line_counter < limit: # if current line is < 5
print(line, end="") # then print the line
line_counter += 1
else: # else, stop looping
break
file_head_display()
<强>说明强>
您的代码段有几个问题:
readline
的每次调用都会消耗一行,因此您使用的for
循环在 5行后开始。