【发布时间】:2019-01-30 16:47:00
【问题描述】:
我想编写一些代码来替换文本文件 (thefile.txt) 中某行上的某个值。我已经寻找了很长时间的解决方案来解决我的问题,但没有找到。
这是我写的代码:
clist = [1, 2, 0, 0, 0, 0]
with open("thefile.txt", "w") as dataFile:
for line in dataFile:
(key, val1, val2 ,val3, val4, val5) = line.split()
if key == clist[0]: #Find correct line
line = line.replace(val1, clist[1]) #Replace the value I want, but not the others
我的文本文件如下所示:
1 0 0 0 13 0
2 9 4 5 2 3
3 0 0 4 0 0
由于某种原因,它不起作用。我仍然是 python 的初学者,所以我相信问题可能在于我试图以写入模式(line.split)“读取”文件。我不知道每行的 line.split 是否被视为阅读。
【问题讨论】:
标签: python python-3.x list file