python中的For循环x从文件中执行的次数
该脚本针对accounts.txt文件中存在的帐户数运行。无论accounts.txt文件中有多少个帐户,我都希望运行脚本x多次。所以我只需输入一个输入10,脚本应该只运行for循环10次。下面是我的代码 有人能帮我修复for循环或为for循环添加新的父循环吗python中的For循环x从文件中执行的次数,python,for-loop,Python,For Loop,该脚本针对accounts.txt文件中存在的帐户数运行。无论accounts.txt文件中有多少个帐户,我都希望运行脚本x多次。所以我只需输入一个输入10,脚本应该只运行for循环10次。下面是我的代码 有人能帮我修复for循环或为for循环添加新的父循环吗 file = open('accounts.txt','r') for line in file: credentials = line.split(";") username = credentials[0]
file = open('accounts.txt','r')
for line in file:
credentials = line.split(";")
username = credentials[0]
password = credentials[1]
comment = credentials[2]
chromedriver = "/Users/Ali/Downloads/chromedriver"
os.environ["webdriver.chrome.driver"] = chromedriver
# driver = webdriver.Chrome(chromedriver)
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--mute-audio")
这应该起作用:
for count, line in enumerate(file):
credentials = line.split(";")
username = credentials[0]
password = credentials[1]
comment = credentials[2]
chromedriver = "/Users/Ali/Downloads/chromedriver"
os.environ["webdriver.chrome.driver"] = chromedriver
# driver = webdriver.Chrome(chromedriver)
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--mute-audio")
if count == 9: # count starts at 0
break
将阅读内容放入函数中:
def run_loop():
file_han = open('accounts.txt','r')
file = file_han.read().split('/n') #you need to read and split the file w.r.t lines
file_han.close()
for line in file:
credentials = line.split(";")
username = credentials[0]
password = credentials[1]
comment = credentials[2]
chromedriver = "/Users/Ali/Downloads/chromedriver"
os.environ["webdriver.chrome.driver"] = chromedriver
# driver = webdriver.Chrome(chromedriver)
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--mute-audio")
#Now loop the function over and over
i=0
while i =! input('Enter iterations no:'):
run_loop()
i=i+1
解决此问题的另一种方法是使用
itertools.islice()
,它允许您从迭代器(例如文件指针)中选择所需的值:
import itertools
with open('accounts.txt', 'r') as file:
wanted_lines = 10
for line in itertools.islice(file, wanted_lines):
credentials = line.split(";")
username = credentials[0]
password = credentials[1]
comment = credentials[2]
chromedriver = "/Users/Ali/Downloads/chromedriver"
os.environ["webdriver.chrome.driver"] = chromedriver
# driver = webdriver.Chrome(chromedriver)
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--mute-audio")
此外,在这里,我使用了带有open…结构的
来打开要读取的文件。这样做的好处是,文件将在到达块的末尾时自动关闭。您可以使用x=0
这样的变量,然后使用而x<10:
作为循环,因为这将循环10次。请发布一个经过审查的帐户示例。txtUse以计算迭代次数,并在达到限制时停止具有myemail@gmail.com;密码;注释很好我修复了我的问题,只需要在它接受输入后将其转换为整数。。非常感谢。。