indexError:仅用于循环的列表索引范围内?
每次循环完成时,我一直在尝试使我的程序读取与文件不同的行。这是第一次起作用,但是一旦第一个循环完成,我就会出现 indexError:列表索引以外的范围。我该如何解决?
标题为 s的文件是18239 线长,标题为 sp的文件长1000 线。
from itertools import count
import time
import webbrowser
import pynput
from pynput.keyboard import Key, Listener, Controller
import random
import string
import secrets
number = random.randint(0,18238)
number2 = random.randint(0,18238)
kb = Controller()
cout = 0
f = open('D:\Scripts\sp.txt', 'r')
fi = open('D:\Scripts\s.txt', 'r')
fil = open('D:\Scripts\s.txt', 'r')
while cout < 1000:
linecount = random.randint(0,999)
line = f.readlines()[linecount]
lines = line.split()
email = lines[0]
password= lines[1]
name = fi.readlines()[number]
name2 = fil.readlines()[number2]
firstname = name.rstrip("\n")
lastname = name2.rstrip("\n")
I've been trying to make my program read a different line from a file each time the loop is completed. This works the first time but once the first loop is completed I am presented with IndexError: list index out of range. How can I fix this?
The file titled s is 18239 lines long and the file titled sp is 1000 lines long.
from itertools import count
import time
import webbrowser
import pynput
from pynput.keyboard import Key, Listener, Controller
import random
import string
import secrets
number = random.randint(0,18238)
number2 = random.randint(0,18238)
kb = Controller()
cout = 0
f = open('D:\Scripts\sp.txt', 'r')
fi = open('D:\Scripts\s.txt', 'r')
fil = open('D:\Scripts\s.txt', 'r')
while cout < 1000:
linecount = random.randint(0,999)
line = f.readlines()[linecount]
lines = line.split()
email = lines[0]
password= lines[1]
name = fi.readlines()[number]
name2 = fil.readlines()[number2]
firstname = name.rstrip("\n")
lastname = name2.rstrip("\n")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
现在考虑到这是什么问题,事实证明Python有问题重新阅读文件,因此您必须将readlines()放在我最终使用read()的循环之外,
这是我为解决该问题所做的工作
此版本的代码完美奏效,没有任何问题(没有重新阅读文件,python会哭泣),此版本也保持代码的目的(要读取每个循环的特定随机行)
now after some consideration I look at what was this issue, turns out python has issues re-reading files and so you have to put the readlines() outside the loop I ended up using read()
Here's what I did to fix the issue
this version of the code worked perfectly with no issues (no re-reading files guys python will cry), this version also keeps the purpose of the code (to read a specific random line each loop)