Python - 用文件中的列替换一行

时间:2016-10-05 12:56:51

标签: python file

很抱歉发布这么简单的问题,但我在谷歌上找不到答案。 我希望我的代码可以做这样的事情 代码:

lines = open("Bal.txt").write
lines[1] = new_value
lines.close()

p.s我希望用值

替换文件中的行

1 个答案:

答案 0 :(得分:0)

xxx.dat之前:

ddddddddddddddddd
EEEEEEEEEEEEEEEEE
fffffffffffffffff

with open('xxx.txt','r') as f:
    x=f.readlines()
x[1] = "QQQQQQQQQQQQQQQQQQQ\n"
with open('xxx.txt','w') as f:
    f.writelines(x)

xxx.dat之后:

ddddddddddddddddd
QQQQQQQQQQQQQQQQQQQ
fffffffffffffffff

注意:f.read()返回一个字符串,而f.readlines()返回一个列表,使您可以替换该列表中的一个事件。
当您下次读取文件时,包含\n(Linux)换行符对于将行[1]与行[2]分开很重要,或者您最终会得到:

ddddddddddddddddd
QQQQQQQQQQQQQQQQQQQfffffffffffffffff