我试图更改文本文件中的一些行而不影响其他行.这就是文本文件中名为"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
Run Code Online (Sandbox Code Playgroud)
我的目标是更改第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)
Run Code Online (Sandbox Code Playgroud)
即使代码有效,我想知道是否有更好更有效的方法来做到这一点?是否可以通过行号读取文件?
Lev*_*sky 10
你可以改进的并不多.但是您必须将所有行写入新文件,无论是更改还是未更改.小改进将是:
with声明;lines在else条款中写入没有格式化(如果适用).应用以上所有内容:
import shutil
with open('test') as old, open('newtest', 'w') as new:
for line in old:
if line.rsplit('|', 1)[-1].strip() == 'number3':
new.write('this is replacement|number7\n')
else:
new.write(line)
shutil.move('newtest', 'test')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27200 次 |
| 最近记录: |