简体   繁体   English

Python readlines() 无法在 for 循环中输出错误

[英]Python readlines() doesn't function outputs bug in for loop

Intro: I'm a beginner python learning syntax at the moment.简介:我目前是 Python 初学者学习语法。 I've come across this concept of reading and writing files natively supported by python.我遇到过 python 原生支持的读取和写入文件的概念。 I've figured to give it a try and find bugs after attempting looping reading and writing commands.在尝试循环读取和写入命令后,我想尝试一下并找出错误。 I wanted to randomly pick a name from a name file and then writing it into a new file.我想从名称文件中随机选择一个名称,然后将其写入一个新文件。 My file includes 19239 lines of names, randrange(18238) generates from 0 - 18238, and, supposedly, would read a randomly read a line between 1 - 18239. The problem is that the code that reads and writes works without the for loop but not with the for loop.我的文件包含 19239 行名称,randrange(18238) 从 0 - 18238 生成,并且据说会随机读取 1 - 18239 之间的一行。问题是读写代码在没有 for 循环的情况下工作,但是不是 for 循环。

My attempt:我的尝试:

from random import randrange
rdname = open("names.dat", "r")
wrmain = open("main.dat", "a")
rdmain = open("main.dat", "r")

for x in range(6):
    nm = rdname.readlines()[randrange(18238)]
    print(str(randrange(18238)) + ": " + nm)
    wrmain.write("\n" + nm)
...

Error code:错误代码:

Exception has occurred: IndexError
list index out of range

rdname.readlines() exhausts your file handle. rdname.readlines()耗尽您的文件句柄。 Running rdname.readlines() gives you the list of lines the first time, but returns an empty list every subsequent time.第一次运行rdname.readlines()会为您提供行列表,但随后每次都会返回一个空列表。 Obviously, you can't access an element in an empty list.显然,您无法访问空列表中的元素。 To fix this, assign the result of readlines() to a variable just once, before your loop.要解决此问题,请在循环之前将readlines()的结果分配给变量一次。

rdlines = rdname.readlines()
maxval = len(rdlines)
for x in range(6):
    randval = randrange(maxval)
    nm = rdlines[randval]
    print(str(randval) + ": " + nm)
    wrmain.write("\n" + nm)

Also, making sure your random number can only go to the length of your list is a good idea.此外,确保您的随机数只能达到列表的长度是一个好主意。 No need to hardcode the length of the list though -- the len() function will give you that.不需要对列表的长度进行硬编码len()函数会给你。

I highly recommend you take a look at how to debug small programs.我强烈建议你看看如何调试小程序。 Using a debugger to step through your code is immensely helpful because you can see how each line affects the values of your variables.使用调试器单步调试代码非常有用,因为您可以看到每一行如何影响变量的值。 In this case, if you'd looked at the value of nm in each iteration, it would be obvious why you got the IndexError , and finding out that nm becomes an empty list on readlines() would point you in the direction of the answer.在这种情况下,如果您在每次迭代中查看nm的值,很明显为什么您会得到IndexError ,并且发现nmreadlines()上变成一个空列表将指向答案的方向.

Good luck with your programming journey.祝你的编程之旅好运。

The readlines() method. readlines()方法。 Has some non-intuitive behaviour.有一些非直觉的行为。 When you use the readlines() it "dumps" the entire content of the file and returns a list of strings of each line.当您使用readlines()它会“转储”文件的全部内容并返回每行的字符串列表。 Thus the second time you call the rdname.readlines()[randrange(18238)] , the rdname file object is completely empty and you actually have an empty list.因此,第二次调用rdname.readlines()[randrange(18238)]rdname文件对象完全为空,实际上您有一个空列表。 So functionally you are telling your programme to run [][randrange(18238)] on the second iteration of the loop.因此,从功能[][randrange(18238)]您是在告诉程序在循环的第二次迭代中运行[][randrange(18238)]

I also took the liberty of fixing the random number call, as the way you had implemented it would mean it would call 2 different random numbers when selecting the name nm = rdname.readlines()[randrange(18238)] and printing the selected name and linenumber print(str(randrange(18238)) + ": " + nm)我还冒昧地修复了随机数调用,因为您实现的方式意味着它会在选择名称nm = rdname.readlines()[randrange(18238)]并打印所选名称时调用 2 个不同的随机数和 linenumber print(str(randrange(18238)) + ": " + nm)

...
rdname = open("names.dat", "r")
wrmain = open("main.dat", "a")
rdmain = open("main.dat", "r")

rdname_list = rdname.readlines()

for x in range(6):
    rd_number = randrange(18238)
    nm = rdname_list[rd_number]
    print(str(rd_number) + ": " + nm)
    wrmain.write("\n" + nm)
...

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM