更新列表中的空值

时间:2018-11-25 14:52:37

标签: python list

所以我有一个文本文件,如下所示:

a,b,

我想更新列表中的空值,这是我的尝试:

def test():
    z=""
    with open("test.txt","r") as user_file:
        for line in user_file.readlines():
            z = line.split(",")
            print(z)
            print(z[2])
    if z[2] not in["1","2","3"]:
        z[2] =="1"
        level = 1
        with open("test.txt","w") as x:
            x=x.write(str(z))
        return level
    else:
        level = z[2]
        return level
x=test()
print(x)

结果如下:

if z[2] not in["1","2","3"]:
IndexError: string index out of range

我只想覆盖txt文件的[2]部分

1 个答案:

答案 0 :(得分:0)

您的if z[2] not in["1","2","3"]代码未在for循环内缩进。 这意味着它看到z变量设置为"",而不是split

产生的变量

请参阅https://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html