他の行に影響を与えることなく、テキスト ファイル内のいくつかの行を変更しようとしています。これが「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)
コードは機能しますが、それを行うためのより良い効率的な方法があるかどうか疑問に思っていますか? 行番号だけでファイルを読み取ることはできますか?