读/写文本文件 [英] Read/Write text file
本文介绍了读/写文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试更改文本文件中的某些行而不影响其他行。这就是文本文件中名为text.txt的内容。
I am trying to change a some lines in a text file without affecting the other lines. This is what's inside the text file called "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行,但保持其余部分相同。
My objective is to change the line 4 and line 5 but keep the rest same.
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)
即使代码有效,我也是想知道是否有任何更好的事情r和有效的方法吗?是否可以通过行号读取文件?
Even though the code works, I am wondering if there is any better and efficient way to do it? Is it possible to read the file just by line number?
推荐答案
你无法改进。但您必须将所有行写入新文件,无论是更改还是未更改。小改进将是:
There is not much you can improve. But you have to write all lines to a new file, either changed or unchanged. Minor improvements would be:
- 使用
和
语句; - 避免在列表中存储行;
- 写入
行
而不在中格式化其他
子句(如果适用)。
- using the
with
statement; - avoiding storing lines in a list;
- writing
lines
without formatting in theelse
clause (if applicable).
应用以上所有内容:
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')
这篇关于读/写文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文