Python:文件中每一行做一些插入操作

来源:互联网 发布:vs编程软件 编辑:程序博客网 时间:2024/05/30 04:10

From_file=open('D:\\python\\A\\niuniu1.txt')Out_file=open('D:\\python\\A\\niuniu2.txt','w')count=0for each_line in From_file:    each_line_list=list(each_line)    each_line_list.insert(0,"'")    Index=each_line_list.index(':')    each_line_list.insert(Index,"'")    each_line_list.insert(Index+2, "'")    Index=each_line_list.index(',')    each_line_list.insert(Index,"'")    Out_file.writelines("".join(each_line_list))    count+=1From_file.close()Out_file.close()

源文件内容:

北京:101010100,
朝阳:101010300,
顺义:101010400,
怀柔:101010500,
通州:101010600,
昌平:101010700,
延庆:101010800,
丰台:101010900,
石景山:10101100,

执行代码后生成文件内容:

'北京':'101010100',
'朝阳':'101010300',
'顺义':'101010400',
'怀柔':'101010500',
'通州':'101010600',
'昌平':'101010700',
'延庆':'101010800',
'丰台':'101010900',
'石景山':'10101100',
'0大兴':'101011100',
'房山':'101011200',
'密云':'101011300',
'门头沟':'101011400',
'平谷':'101011500',
'八达岭':'101011600',
'佛爷顶':'101011700',
'汤河口':'101011800',