Python错误 - 无法查看结果

时间:2014-06-28 16:45:15

标签: python

我正在尝试编写一个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()

我正在使用一个名为names.txt的8行文件。该文本文件的内容如下:

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

当我运行python程序时,我没有输出。我哪里错了?

3 个答案:

答案 0 :(得分:3)

只有print(),它本身只会打印换行符,而不是其他内容。您需要将line变量传递给print()

print(line)

line字符串最后会有换行符,您可能想要print不要添加其他内容:

print(line, end='')

或者您可以删除换行符:

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

答案 1 :(得分:0)

正如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

答案 2 :(得分:-1)

为了打印前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

希望上面的代码能满足您的查询。

谢谢。