Python文件讀寫 - 讀一個文件所有行,加工后寫另一個文件


 

 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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM