简体   繁体   中英

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. 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. 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. Where am I going wrong?

Just print() , by itself, will only print a newline, nothing else. You need to pass the line variable to print() :

print(line)

The line string will have a newline at the end, you probably want to ask print not to add another:

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. Python is interpreted line by line. When the interpreter arrives at your print() line, it is not aware that you want it to print the "line" variable assigned above.

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. You should close the file outside of your for loop. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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