Python按行讀取文件、寫文件


Python按行讀取文件

學習了:https://www.cnblogs.com/scse11061160/p/5605190.html

 

file = open("sample.txt") 
for line in file:
    pass # do something
file.close()

 

學習了:https://blog.csdn.net/ysdaniel/article/details/7970883

去除換行符

for line in file.readlines():  
     line=line.strip('\n')  

 

學習了:https://www.cnblogs.com/feiyueNotes/p/7897064.html

mobile = Method.createPhone()
file = r'D:\test.txt'
with open(file, 'a+') as f:
     f.write(mobile+'\n')   #加\n換行顯示

 

'r':讀
'w':寫
'a':追加
'r+' == r+w(可讀可寫,文件若不存在就報錯(IOError))
'w+' == w+r(可讀可寫,文件若不存在就創建)
'a+' ==a+r(可追加可寫,文件若不存在就創建)
對應的,如果是二進制文件,就都加一個b就好啦:
'rb'  'wb'  'ab'  'rb+'  'wb+'  'ab+'

 


免責聲明!

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



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