1. 程式人生 > >python練習六十二:文件處理,往文件中所有添加指定的前綴

python練習六十二:文件處理,往文件中所有添加指定的前綴

文件處理 pytho += txt mat write 執行 nbsp 格式

往文件中所有添加指定的前綴

方法一:open方法

f_r = open(‘text.txt‘)
f_w = open(‘text_new.txt‘,‘w+‘)
i = 0
while True:
    i += 1
    line = f_r.readline()
    if not line:
        break
    f_w.write(‘%02d‘%i + ‘.python‘+ ‘ ‘ +line)
f_r.close()
f_w.close()
f_wr = open(‘text_new.txt‘,‘r‘)
lines = f_wr.readlines()
for i in lines:
    print
(i) f_wr.close()
方法二:with open方法

with open(‘text.txt‘) as f_r:
line = f_r.readline()
with open(‘text_new.txt‘,‘w‘) as f_w:
i = 0
while True:
i += 1
line = f_r.readline()
if not line:
break
# f_w.write(‘%02d‘%i + ‘.python‘+ ‘ ‘len+line) #格式化輸出方法一
f_w.write(‘{:>2}{}{}{}‘.format(i,‘.python‘,‘ ‘,line)) #格式化輸出方法二

with open(‘text_new.txt‘,‘r‘) as f_wr:
lines = f_wr.readlines()
for i in lines:
print(i)

執行結果:

01.python jave
02.python go
03.python shell
04.python perl

python練習六十二:文件處理,往文件中所有添加指定的前綴