-2

我有一个类似示例的“test.txt”文件,其中包含:

 --
a
 --
b
 --
c

和我的 Python 代码:

x = ['a','b','c']
i=1
with open("test.txt", "r") as fin:
    with open("result.log", "w") as fout:
        for line in fin:
            if line.startswith(' --'):
                fout.write(line.replace(' --','use {}'.format(str(x[i-1]))))
                i+=i
            else:
                fout.write(line)

但结果是:

fout.write(line.replace(' --','use {}'.format(str(x[i-1]))))
IndexError: list index out of range

应该工作......有人可以帮助我吗?我想要结果:

use a
a
use b
b
use c
c
4

3 回答 3

1

在 Python 中,增量运算符看起来像这样i+=1但是您尝试使用i+=i它总是递增 i=i+i

当 i=1 然后在增量 i=2 之后

当 i=2 然后在增量 i=4 之后

您在数组中有三个元素,因此它会给出错误索引。

于 2017-12-15T13:42:31.530 回答
0

i+=i导致异常。您可以使用:

i = 0
// code goes here
i += 1
于 2017-12-15T14:35:11.207 回答
0

用 0初始化i,然后在循环中将其递增 1。此外,您不必调用str(),因为format()它会为您完成。尝试这个:

x = ['a', 'b', 'c']
i = 0

with open("test.txt", "r") as fin, open("result.log", "w") as fout:    
    for line in fin:
        if line.startswith(' --'):
            fout.write(line.replace(' --','use {}'.format(x[i])))
            i += 1
        else:
            fout.write(line)

输出写入result.log

use a
a
use b
b
use c
c
于 2017-12-15T13:06:32.030 回答