【发布时间】:2022-11-30 03:03:40
【问题描述】:
如何将字符串/整数添加到特定位置的现有文本文件中?
我的示例文本如下所示:
No, Color, Height, age
1, blue,70,
2, white,65,
3, brown,49,
4, purple,71,
5, grey,60,
我的文本文件有 4 列,三列有文本,我如何写入第四列中的任何一行?
如果我想将 12 写入第二行,更新后的文件 (sample.txt) 应该如下所示:
No, Color, Height, age
1, blue,70,12
2, white,65,
3, brown,49,
4, purple,71,
5, grey,60,
我试过这个:
with open("sample.txt",'r') as file:
data =file.readlines()
data[1]. split(",") [3] = 1
with open ('sample.txt', 'w') as file:
file.writelines(data)
with open ('sample.txt', 'r') as file:
print (file. Read())
但它不起作用。需要你的帮助。
【问题讨论】:
-
您在拆分后编辑了该行,但未对原始行进行任何更改。在执行拆分和变异后尝试
data[1] = split_data_1.join(',')或类似的。
标签: python text overwrite file-writing