python 文件操作之open,read,write


1、open

#open(filepath , 'mode')

file = open(‘D:\test\test.txt’,‘w’)   #存在問題見FAQ1

一般常用模式:r(只讀)、w(只寫)、a(追加)、b(二進制)

組合:r+(讀寫)、w+(讀寫)  #存在問題見FQA2

2、讀文件(r): read()         readline()           readlines()

file = open('D/test/test.txt','r')   #只讀模式打開file

all_txt = file.read()  #讀全部

one_line_txt = file.readline()   #讀一行

all_line_txt = file.readlines()  #讀所有行

 

3、讀固定字節文件

file = open('D/test/test.txt','b')   #只讀模式打開file

200_byte = file.read(200)

 

4、寫文件(w)

file = open('D/test/test.txt','w')   #只寫模式打開file

 input= file.write('11111')

list = ['1111','22222','33333']

input_lines = file.writelines(list)  #寫入的參數放入一個列表中,寫多行

 

https://docs.python.org/2.7/tutorial/inputoutput.html#methods-of-file-objects

FQA1:報錯

 

無效的模式或者文件

 

關於python絕對路徑的書寫方式

 

  • 改為file = open(r‘D:\test\test.txt’,‘w’) 
  • 改為file = open('D:/test/test.txt’,‘w')  表示絕對路徑是使用正斜杠

 

FAQ2:

讀寫模式在windows 下,同時調用會出現亂碼。盡量分開使用

https://segmentfault.com/q/1010000000397712

 


免責聲明!

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



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