2014-01-21 28 views
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() 

回答

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消耗一條線,S您正在使用的for迴路開始第5行。
  • for循環迭代文件中的一行;它不是線的計數器(所以轉換成int是一個爛攤子)
  • 請使用環明智的,不要寫一樣的東西5倍
+0

謝謝你給了工作的代碼。我仍然在弄清楚你提供的代碼中不同的陳述是做什麼的。謝謝! –

相關問題