python - 替换python文件中的行
问题描述
我想编写一个给出一些整数值的程序。我有一个文件,第一行有一个值。如何更改 line 的值(例如更改为 12)。这是我的代码,但是它得到了一个值,我想转到第 2 行并将 m 添加到第 2 行中的那个数字,但它不起作用。
t=open('pash.txt', 'r')
g=[]
for i in range(3):
g.append(t.readline())
t.close()
g[o-1]=(int(g[o-1]))+m # o is the number of line in file
print(g[o-1])
t=open("pash.txt","w")
for i in range(3):
t.write(str(g[i]))
t.write('\n')
t.close()
解决方案
您可以open
使用 逐行读取文件readlines
,修改内容并重新write
文件:
with open('pash.txt', 'r') as f:
lines = f.readlines()
m = 5 # value you need to add to a line.
o = 2 # line number of the line to modify.
with open('pash.txt', 'w') as f:
for x, line in enumerate(lines):
if x == o:
line = int(line) + m
f.write(line)
推荐阅读
- groovy - Jira Plug-in ScriptRunner Escalation Service:post请求会继续返回缓存响应
- c# - Unity C# Vector3.Distance 产生意想不到的结果
- jquery - Bootstrap 5 模态窗口阻止 preventDefault() 事件在第二次发送时起作用
- python - 钥匙圈显然没有用 pip macos 正确安装
- python - 为什么 x_train 和 y_train 的形状不同,而它们的值由一个数据集分配?
- makefile - 如何在我自己的应用程序中设置 configure.ac (autoconf) 以自动发现 LAPACK、ATLAS、OpenBLAS 和 KMP?
- workflow - 有没有更快的方法来获取 workflowHistory
- angular - 如何等待 Typescript 中 for 循环的结果?
- docker - 在远程 Docker 上的 VS Code 中运行 Jupyter
- java - Karatsuba 算法将数字拆分为 3 个字符串