簡體   English   中英

Python錯誤-無法看到結果

[英]Python error - unable to see result

我正在嘗試編寫一個python程序,要求用戶輸入現有文本文件的名稱,然后顯示文本文件的前5行或完整文件(如果少於5行)。 到目前為止,這是我編程的內容:

def main():
    # Ask user for the file name they wish to view
    filename = input('Enter the file name that you wish to view: ')

    # opens the file name the user specifies for reading
    open_file = open(filename, 'r')

    # reads the file contents - first 5 lines   
    for count in range (1,6):
        line = open_file.readline()

        # prints the contents of line
        print()

main()

我正在使用一個包含8行的文件,稱為names.txt。 該文本文件的內容如下:

Steve Smith
Kevin Applesauce
Mike Hunter
David Jones
Cliff Martinez
Juan Garcia
Amy Doe
John Doe

當我運行python程序時,沒有輸出。 我要去哪里錯了?

print()本身僅會打印換行符,僅此而已。 您需要將line變量傳遞給print()

print(line)

line字符串的末尾會有一個換行符,您可能想讓print不要添加另一個:

print(line, end='')

或者您可以刪除換行符:

print(line.rstrip('\n'))

正如Martijn所說,print()命令帶有一個參數,該參數就是您要打印的參數。 Python是逐行解釋的。 當解釋器到達您的print()行時,它不知道您是否希望它打印上面分配的“ line”變量。

另外,最好關閉已打開的文件,以釋放該內存,盡管在許多情況下,Python會自動處理此問題。 您應該在for循環之外關閉文件。 即:

for count in range(5): #it's simpler to allow range() to take the default starting point of 0. 
    line = open_file.readline()
    print(line)
open_file.close() # close the file

為了先打印5行或更少的行。 您可以嘗試以下代碼:

 filename = input('Enter the file name that you wish to view: ')
   from itertools import islice
   with open(filename) as myfile:
     head = list(islice(myfile,5))
   print head

希望以上代碼能滿足您的查詢。

謝謝。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM