Search code examples
pythonfilelinetry-except

How to read the whole line?


I try to ask user for the line number and display it but it keep showing the first letter not the line.

And I can't figure it out how to loop the IoError and IndexError.

Thank you

This is my code

def file_content(file_name):
    user_file = open(file_name, 'r')
    content = user_file.read()
    user_file.close()
    return content
def main():
    file_name = input('Enter the name of the file: ')



    try:
       content = file_content(file_name)
    

    except IOError:
       print ('File can not be fount. Program wil exit.')
       exit()

    try:
    
       line_number = int(input('Enter a line number: '))

    except ValueError:
        print ('You need to enter an integer for the line number. Try again.')

    except IndexError:
        print ('that is not a valid line number. Try again.')

    
    print ('The line you requested:')
    print (content[line_number-1])

 main()

Solution

  • content is simply the content of the file as your use read() - so printing content[-1] prints the last thing in content, i.e. the last character.

    If you want content to be lines, the a) open the file ‘rt’ and b) read it using readlines() which you might need to note includes the line ending with the line:

    def file_content(file_name):
        user_file = open(file_name, 'rt')
        content = user_file.readlines()
        user_file.close()
        return content
    

    Now content[-1] is th last line.