前幾天無意間看見一道題,內容大致是這樣的。有一個文件,裏面內容是這樣的格式
1 aa
2 bb
3 cc
4 dd
現在想插入3 ee,如果存在3 那麼把後面內容換成新內容,如果不存在則添加一行。一開始我是這麼寫的
tmp=[]
with open('1','r') as fd:
lock=0
a=fd.readlines()
for line in a:
if '3' in line:
line=line.replace('cc','ee')
lock=1
tmp.append(line)
if lock==0:
tmp.append('3 ee')
with open('1','w') as fd:
for line in tmp:
fd.write(line)
後來經指點使用字典可以這麼寫
tmp={}
with open('1','r') as fd:
a=fd.readlines()
for line in a:
tmp[line.split()[0]]=line.split()[1]
tmp['3']='ee'
這樣就可以讀出來並且修改或者添加,但是卻有一個問題。字典是無序的,所以不能保證寫入文件時候保證順序,所以還得排序之後才能寫進去,排序之後變成了list,每個元素是tuple類型,這時候轉成字符串是有()的,所以使用join連接變成字符串。
with open('1','w') as fd:
tmp=sorted(tmp.iteritems(),key=lambda d:d[0])
for i in tmp:
fd.write(' '.join(i)+'\n')