1 #Filename: file_read_and_write.py 2 #打開文件,cNames讀取所有行,儲存在列表中,循環對每一行在起始處加上序號1,2,3,4 3 with open(r'file/companies.txt') as f1: 4 cNames = f1.readlines() 5 for i in range(0,len(cNames)): 6 cNames[i] = str(i+1) + '.' + '' + cNames[i] 7 8 #將處理過的cNames寫入新的文件中 9 with open(r'file/scompanies.txt','w') as f2: 10 f2.writelines(cNames)
輸入: companies.txt
google
tencent
alibaba
baidu
輸出:scompanies.txt
1.google
2.tencent 3.alibaba 4.baidu
