为什么我不能将行添加到新文件中?

时间:2018-02-17 19:35:44

标签: python-3.x append lines

我想创建一个新文件,我一次追加一行,就像打印输出一样:

with open("file") as file:
    for line in file:
        if line[0]==">":
            i=1
            while line[i]!=" ":
                line[i]
                i+=1
                print(line[i],end='')
            print("\n")    

我最好的猜测是使用此代码:

with open("newfile", "a") as newfile: 
    with open("file") as file:
        for line in file:
            if line[0]==">":
                i=1
                while line[i]!=" ":
                    line[i]
                    i+=1
                    newfile.write(line[i],end='')
                newfile.write("\n") 

但我明白了:

File "<ipython-input-40-7a0d2eb4e1ca>", line 9, in <module>
  newfile.write(line[i],end='')

IndexError: string index out of range

2 个答案:

答案 0 :(得分:0)

您收到此错误是因为在检查行[i] ==“”之前没有检查字符串的长度。

while line[i] == " ":

while (i < len(line)) && (line[i] == " "):

答案 1 :(得分:0)

为什么在写行前更改索引i?您应该在写完后增加i,否则您可能会将设置行设置为超出界限的值。