0
這是一項家庭作業,我似乎無法弄清楚。程序打印單獨的行而不是整個文件
「編寫一個程序,要求用戶輸入文件的名稱,程序只顯示文件內容的前五行,如果文件的內容少於五行,應該顯示文件的全部內容。 「
只要程序讀取多於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()
謝謝你給了工作的代碼。我仍然在弄清楚你提供的代碼中不同的陳述是做什麼的。謝謝! –