[英]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.