简体   繁体   中英

why getting lis index out of range error while reading file with readlines()?

I'm only a python beginner so I wanted to practice reading and writing files. (I'm using python 3)

Decision = input("""Would you like to 'Write' (W)?
                \nWould you like to 'Read' (R)?""")

if Decision == "W":
    fileInput = input("What file Would you like to Write to?")
    write(fileInput)

elif Decision == "R":
    fileInput = input("What file would you like to Read?")
    lineNoInput = input("How many lines would you like to read?")
    read(fileInput, lineNoInput)

I wanted to make a program that lets you read and write files. I haven't worked on writing to them yet but the I'm working on making a read() function which keeps spitting out errors.

def read(file, lineNo):
    fileName = file + ".txt"
    text_file = open(fileName, "r")

    lineNo = int(lineNo)

    for x in range(0, lineNo - 1):
        print(text_file.readlines()[x])

    text_file.close()

For some reason which I can't work out, the user input that decides how many lines to read keeps spitting out an Index error.

我的错误信息

Sorry If my code is clumsy or ineffective, as I said before I'm still a beginner and I would appreciate any input on why this is happening.

 for x in range(0, lineNo - 1): print(text_file.readlines()[x])

the bug in calling readlines method. The readlines() method returns a list containing each line in the file as a list item. this method should be called once only!! calling it for the next time you will get empty list []

if you want to read the file line by line then use the context manger with for reading files in general.

Technically, in Python, an iterator is an object which implements the iterator protocol , which consist of the methods __iter__() and __next__() . since file are folowing the iterator protocol you can read them with for loop:

with open (fileName,'r') as fP:
    for line in fp:
        #do work

No need to call close(). this is handle by the context manager after exiting the with block the file will be closed.

for limiting the number of lines to be read, it simple use lines counter while iterating over the file:

lines_num = 10
with open (fileName,'r') as fP:
    for line in fp:
        #do work
        lines_num -= 1
        if not lines_num: break

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