[英]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.