本篇內容主要講解“Python怎么進行讀寫文件”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“Python怎么進行讀寫文件”吧!
| Character | Meaning |
|---|---|
| ‘r’ | open for reading (default) |
| ‘w’ | open for writing, truncating the file first |
| ‘a’ | open for writing, appending to the end of the file if it exists |
| ‘b’ | binary mode |
| ‘t’ | text mode (default) |
| ‘+’ | open a disk file for updating (reading and writing) |
| ‘U’ | universal newline mode (for backwards compatibility; should not be used in new code) |
| 模式 | 描述 |
|---|---|
| rt | 讀取文本,默認模式 |
| rb | 讀取二進制數據 |
| wt | 寫入文本 |
| wb | 寫入二進制 |
| r+ | 不清空原文件,讀寫 |
| w+ | 清空原文件,并讀寫 |
| a+ | 在文件末尾讀寫 |
首先在左面新建一個”abc.txt”的文件,文件的內容入如下:
I
love
CSDN
只讀模式(默認模式)
>>>>f=open("C:/Users/Administrator/Desktop/abc.txt","r")
>>>>print(f.read())
I
love
CSDN
>>>>f.close()寫入模式
>>>>f=open("C:/Users/Administrator/Desktop/abc.txt","w")
>>>>f.write("test")
>>>>f.close()輸出的結果是:
test
在使用”w”模式時,python會把原來的文件給覆蓋掉,形成新的文件,這里注意如果寫入的文件不存在,python會自動新建一個文件。
追加模式
>>>>f=open("C:/Users/Administrator/Desktop/abc.txt","a")
>>>>f.write("test")
>>>>f.close()輸出的結果是:
I
love
CSDNtest
另外我們還可以設定讀取和寫入的方式:
以二進制方式讀?。?/p>
>>>>f=open("C:/Users/Administrator/Desktop/abc.txt","rb")
>>>>print(f.read())
>>>>f.close()
b'I\r\nlove\r\nCSDN'而以二進制讀取的一個妙用就是保存matplotlib的交互式圖片頁面:
保存交互式圖片頁面
import matplotlib.pyplot as pltimport pickle as pl#調用matplotlib的figure對象fig = plt.figure()
x = [1,2,3,4,5]
y = [1,2,3,4,5]
plt.plot(x,y)#序列化figure對象,并保存pl.dump(fig,open('C:/Users/Administrator/Desktop/fig.pickle','wb'))讀取交互式頁面:
import matplotlib.pyplot as pltimport pickle as pl# 載入序列化文件fig = pl.load(open('C:/Users/Administrator/Desktop/fig.pickle','rb'))
plt.show()# 獲得圖片信息print(fig.axes[0].lines[0].get_data())到此,相信大家對“Python怎么進行讀寫文件”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。