所以我有一个文本文件,如下所示:
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]部分
答案 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