简体   繁体   English

Python错误-无法看到结果

[英]Python error - unable to see result

I am trying to write a python program that asks the user to enter an existing text file's name and then display the first 5 lines of the text file or the complete file if it is 5 lines or less. 我正在尝试编写一个python程序,要求用户输入现有文本文件的名称,然后显示文本文件的前5行或完整文件(如果少于5行)。 This is what I have programmed so far: 到目前为止,这是我编程的内容:

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()

I am using a file that has 8 lines in it called names.txt. 我正在使用一个包含8行的文件,称为names.txt。 The contents of this text file is the following: 该文本文件的内容如下:

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

When I run the python program, I get no output. 当我运行python程序时,没有输出。 Where am I going wrong? 我要去哪里错了?

Just print() , by itself, will only print a newline, nothing else. print()本身仅会打印换行符,仅此而已。 You need to pass the line variable to print() : 您需要将line变量传递给print()

print(line)

The line string will have a newline at the end, you probably want to ask print not to add another: line字符串的末尾会有一个换行符,您可能想让print不要添加另一个:

print(line, end='')

or you can remove the newline: 或者您可以删除换行符:

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

As Martijn said, the print() command takes an argument, and that argument is what it is you'd like to print. 正如Martijn所说,print()命令带有一个参数,该参数就是您要打印的参数。 Python is interpreted line by line. Python是逐行解释的。 When the interpreter arrives at your print() line, it is not aware that you want it to print the "line" variable assigned above. 当解释器到达您的print()行时,它不知道您是否希望它打印上面分配的“ line”变量。

Also, it's good practice to close a file that you've opened so that you free up that memory, though in many cases Python takes care of this automatically. 另外,最好关闭已打开的文件,以释放该内存,尽管在许多情况下,Python会自动处理此问题。 You should close the file outside of your for loop. 您应该在for循环之外关闭文件。 Ie: 即:

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

In order to print first 5 or less lines. 为了先打印5行或更少的行。 You can try the following code: 您可以尝试以下代码:

 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

Hope the above code will satisfy your query. 希望以上代码能满足您的查询。

Thank you. 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM