# Python 文件處理
> 原文: [https://thepythonguru.com/python-file-handling/](https://thepythonguru.com/python-file-handling/)
* * *
于 2020 年 1 月 7 日更新
* * *
我們可以使用文件處理來讀寫文件中的數據。
## 打開文件
* * *
在讀/寫之前,您首先需要打開文件。 打開文件的語法是。
```py
f = open(filename, mode)
```
`open()`函數接受兩個參數`filename`和`mode`。 `filename`是一個字符串參數,用于指定文件名及其路徑,而`mode`也是一個字符串參數,用于指定文件的使用方式,即用于讀取或寫入。 `f`是文件處理器對象,也稱為文件指針。
## 關閉文件
* * *
讀/寫完文件后,您需要使用`close()`這樣的方法關閉文件,
```py
f.close() ?# where f is a file pointer
```
## 打開文件的不同模式
* * *
| 模式 | 描述 |
| --- | --- |
| `"r"` | 打開文件以只讀 |
| `"w"` | 打開文件進行寫入。 如果文件已經存在,則在打開之前將清除其數據。 否則將創建新文件 |
| `"a"` | 以附加模式打開文件,即將數據寫入文件末尾 |
| `"wb"` | 打開文件以二進制模式寫入 |
| `"rb"` | 打開文件以二進制模式讀取 |
現在讓我們看一些示例。
## 將數據寫入文件
* * *
```py
>>> f = open('myfile.txt', 'w') # open file for writing
>>> f.write('this first line\n') # write a line to the file
>>> f.write('this second line\n') # write one more line to the file
>>> f.close() # close the file
```
**注意**:
`write()`方法不會像`print()`函數那樣自動插入新行(`'\n'`),需要顯式添加`'\n'`來編寫`write()`方法。
## 從文件讀取數據
* * *
要從文件讀回數據,您需要以下三種方法之一。
| 方法 | 描述 |
| --- | --- |
| `read([number])` | 從文件中返回指定數量的字符。 如果省略,它將讀取文件的全部內容。 |
| `readline()` | 返回文件的下一行。 |
| `readlines()` | 讀取所有行作為文件中的字符串列表 |
## 一次讀取所有數據
* * *
```py
>>> f = open('myfile.txt', 'r')
>>> f.read() # read entire content of file at once
"this first line\nthis second line\n"
>>> f.close()
```
將所有行讀取為數組。
```py
>>> f = open('myfile.txt', 'r')
>>> f.readlines() # read entire content of file at once
["this first line\n", "this second line\n"]
>>> f.close()
```
只讀一行。
```py
>>> f = open('myfile.txt', 'r')
>>> f.readline() # read the first line
"this first line\n"
>>> f.close()
```
## 附加數據
* * *
要附加數據,您需要以`'a'`模式打開文件。
```py
>>> f = open('myfile.txt', 'a')
>>> f.write("this is third line\n")
19
>>> f.close()
```
## 使用`for`循環遍歷數據
* * *
您可以使用文件指針遍歷文件。
```py
>>> f = open('myfile.txt', 'r')
>>> for line in f:
... print(line)
...
this first line
this second line
this is third line
>>> f.close()
```
## 二進制讀寫
* * *
要執行二進制 I/O,您需要使用一個名為`pickle`的模塊。 `pickle`模塊允許您分別使用`load`和`dump`方法讀取和寫入數據。
## 寫入二進制數據
* * *
```py
>> import pickle
>>> f = open('pick.dat', 'wb')
>>> pickle.dump(11, f)
>>> pickle.dump("this is a line", f)
>>> pickle.dump([1, 2, 3, 4], f)
>>> f.close()
```
## 讀取二進制數據
* * *
```py
>> import pickle
>>> f = open('pick.dat', 'rb')
>>> pickle.load(f)
11
>>> pickle.load(f)
"this is a line"
>>> pickle.load(f)
[1,2,3,4]
>>> f.close()
```
如果沒有更多數據要讀取,則`pickle.load()`會引發`EOFError`或文件結尾錯誤。
在下一課中,我們將學習 python 中的[類和對象](/python-object-and-classes/)。
* * *
* * *
- 初級 Python
- python 入門
- 安裝 Python3
- 運行 python 程序
- 數據類型和變量
- Python 數字
- Python 字符串
- Python 列表
- Python 字典
- Python 元組
- 數據類型轉換
- Python 控制語句
- Python 函數
- Python 循環
- Python 數學函數
- Python 生成隨機數
- Python 文件處理
- Python 對象和類
- Python 運算符重載
- Python 繼承與多態
- Python 異常處理
- Python 模塊
- 高級 Python
- Python *args和**kwargs
- Python 生成器
- Python 正則表達式
- 使用 PIP 在 python 中安裝包
- Python virtualenv指南
- Python 遞歸函數
- __name__ == "__main__"是什么?
- Python Lambda 函數
- Python 字符串格式化
- Python 內置函數和方法
- Python abs()函數
- Python bin()函數
- Python id()函數
- Python map()函數
- Python zip()函數
- Python filter()函數
- Python reduce()函數
- Python sorted()函數
- Python enumerate()函數
- Python reversed()函數
- Python range()函數
- Python sum()函數
- Python max()函數
- Python min()函數
- Python eval()函數
- Python len()函數
- Python ord()函數
- Python chr()函數
- Python any()函數
- Python all()函數
- Python globals()函數
- Python locals()函數
- 數據庫訪問
- 安裝 Python MySQLdb
- 連接到數據庫
- MySQLdb 獲取結果
- 插入行
- 處理錯誤
- 使用fetchone()和fetchmany()獲取記錄
- 常見做法
- Python:如何讀取和寫入文件
- Python:如何讀取和寫入 CSV 文件
- 用 Python 讀寫 JSON
- 用 Python 轉儲對象