简体   繁体   中英

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

content is simply the content of the file as your use read() - so printing content[-1] prints the last thing in content, ie 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.

barny has a good answer, but using readlines() isn't a best practice . You might consider replacing your file_content function with something that doesn't load the entire file into memory at once, like this:

def file_content(filename):
  result = []
  with open(filename, 'r') as input_file:
    result = list(input_file)
  return result

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