使该脚本用于从文本文档中读取文件名和文件路径,打印文件名,然后运行文件。该文件是progs.conf,看起来像这样:
[prog.1]
Name:NotepadPlusPlus
Path:C:\Program Files (x86)\Notepad++\notepad++.exe
脚本为:
import subprocess
progList = open("progs.conf", "r")
numLines = sum(1 for line in progList)
repeatTimes = numLines / 3
counter = 0
while counter <= repeatTimes:
print("Opening " + str(progList.readlines()[counter + 1][6:]) + "...")
subprocess.Popen(str(progList.readlines()[counter + 2][6:]))
counter = counter + 1
它吐出了这个错误:
文件launcher.py”,第
行,第16行print(“ Opening” + str(progList.readlines()[counter + 1] [6:])+“ ...”)
IndexError:列表索引超出范围
答案 0 :(得分:1)
readlines
我不在Windows上,所以我稍微编辑了您的conf文件
考虑这个
import subprocess
with open("progs.conf", "r") as progList:
lines = progList.readlines()
ilines = iter(lines)
sets = zip(ilines,ilines,ilines)
for bname, prog, path in sets:
print "Processing " + str(bname)
print "Launching " + str(prog.split(":")[1])
print "PAth: " + path.split(":")[1]
subprocess.Popen(str(path.split(":")[1]), shell=True)
conf文件如下所示
$ cat progs.conf
[prog.1]
Name:NotepadPlusPlus
Path:gvim
lines = progList.readlines()
ilines = iter(lines)
读取一次文件,并为读取的行列表创建迭代器。
然后,您可以执行sets = zip(ilines,ilines,ilines)
将此序列存储在3个组中。for bname, prog, path in sets:
遍历此3个组的列表。