简体   繁体   English

为什么在使用 readlines() 读取文件时出现 lis 索引超出范围错误?

[英]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.我只是一个 python 初学者,所以我想练习读写文件。 (I'm using python 3) (我正在使用 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.我还没有写信给他们,但是我正在做一个 read() function ,它不断吐出错误。

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.调用 readlines 方法的错误。 The readlines() method returns a list containing each line in the file as a list item. readlines()方法返回一个列表,其中包含文件中的每一行作为列表项。 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__() .从技术上讲,在 Python 中,迭代器是实现iterator protocol的 object,它由方法__iter__()__next__()组成。 since file are folowing the iterator protocol you can read them with for loop:由于文件遵循iterator protocol ,您可以使用 for 循环读取它们:

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

No need to call close().无需调用 close()。 this is handle by the context manager after exiting the with block the file will be closed.这是在退出 with 块后由上下文管理器处理的,文件将被关闭。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 索引超出范围,文件读取行 - Index out of range, file readlines python 文件阅读列表索引错误:索引超出范围 - python file reading list index error: index out of range 从文件读取多行时在python中索引超出范围 - Index out of range in python while reading multiple lines from a file 索引超出范围,无法在Python中进行简单的“ readlines”操作 - Index out of range for simple `readlines` operation in Python 为什么在 python 中使用 face_recognition 库时出现列表索引超出范围错误? - Why am I getting a list index out of range error while using face_recognition library in python? Python 中的列表索引超出范围错误(读取 CSV 文件) - list index out of range error in Python ( reading CSV file) 获取错误消息:切片列表时列表索引超出范围? - getting Error msg: List index out of range while slicing a list? 获取 IndexError:在 bigquery 中加载文件时字符串索引超出范围 - Getting IndexError: string index out of range while loading file in bigquery 出现“索引超出范围”错误 - Getting a “ index out of range ” error 在python中写入XML文件时,为什么会出现子索引超出范围的错误? - Why am I getting child index out of range error when I writing to XML file in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM