【发布时间】:2013-05-12 08:57:00
【问题描述】:
我正在尝试更改文本文件中的某些行而不影响其他行。这就是名为“text.txt”的文本文件中的内容
this is a test1|number1
this is a test2|number2
this is a test3|number2
this is a test4|number3
this is a test5|number3
this is a test6|number4
this is a test7|number5
this is a test8|number5
this is a test9|number5
this is a test10|number5
我的目标是更改第 4 行和第 5 行,但其余部分保持不变。
mylist1=[]
for lines in open('test','r'):
a=lines.split('|')
b=a[1].strip()
if b== 'number3':
mylist1.append('{}|{} \n'.format('this is replacement','number7'))
else:
mylist1.append('{}|{} \n'.format(a[0],a[1].strip()))
myfile=open('test','w')
myfile.writelines(mylist1)
即使代码有效,我想知道是否有更好更有效的方法来做到这一点?是否可以仅按行号读取文件?
【问题讨论】:
-
不能在任意位置写入'a line',但如果想在读取时知道当前行号,可以使用
enumerate,如for index, line in enumerate(open('test','r')):。如果您真的想通过编号而不是位置来识别行,这可能会有所帮助。顺便说一句:像你这样写'for lines'会产生误导——你每次通过循环得到的是一个single行。