# 10. 檔案讀寫

## I. 讀檔

通常有兩種方式：\
方法一：

```python
f = open(<檔名>) # 讀檔一般習慣將它存在名稱為f的變數裡
```

不過使用完畢後要記得關閉它

```python
f.close()
```

方法二：\
【此方式使用完畢後會自動關閉檔案，因此較推薦】

```python
with open(<檔名>) as f:
```

【比較看看】

> 假設你現在正在編輯的檔案名稱為`main.py`請你在同個目錄下創造出另一個`.py`(如圖中的`moduleA.py`)檔並嘗試用程式`open`它\
> ![](https://i.imgur.com/OohzxQ8.png)

方法一：

```python
f = open("moduleA.py")
print(f.closed) # False (還未關閉)
f.close()
```

方法二：

```python
with open("moduleA.py") as f:
    print(f.closed) # False (還未關閉)
print(f.closed) # True (已關閉)
```

### A.開檔模式 <a href="#kai-dang-mo-shi" id="kai-dang-mo-shi"></a>

開啟檔案時需指名開檔模式，根據開啟的模式，只能使用限定的功能\
寫法：【`open(<檔名>, <模式>)`】<br>

| 模式 | 功能    | 若存在此檔名 | 寫入方式                           | 若不存在此檔名 |
| -- | ----- | ------ | ------------------------------ | ------- |
| r  | 讀取    | 讀取     |                                | Error   |
| r+ | 寫入+讀取 | 讀取     | <p>從第一列開始覆蓋<br>(並沒有整個檔案覆蓋)</p> | Error   |
| w  | 寫入    | 整個檔案覆蓋 | 整個檔案覆蓋                         | 開新檔案    |
| w+ | 寫入+讀取 | 整個檔案覆蓋 | 整個檔案覆蓋                         | 開新檔案    |
| a  | 寫入    | 讀取     | 接續                             | 開新檔案    |
| a+ | 寫入+讀取 | 讀取     | 接續                             | 開新檔案    |

### B.開檔後讀取檔案內容 <a href="#kai-dang-hou-du-qu-dang-an-nei-rong" id="kai-dang-hou-du-qu-dang-an-nei-rong"></a>

```python
with open("moduleA.py", "r") as f:
    s = f.read() 
    print(s)
```

## II.寫檔

### A. 開檔後寫入檔案內容 <a href="#kai-dang-hou-xie-ru-dang-an-nei-rong" id="kai-dang-hou-xie-ru-dang-an-nei-rong"></a>

【試試看看】

> 下列三種方法的結果有何不同?

```python
# 請先自行新增file_r.txt空檔
for k in range(3):
    with open('file_r.txt', 'r+') as f:
        f.write(f'this is line {k}\n')
```

```python
# 請先自行新增file_w.txt空檔
for k in range(3):
    with open('file_w.txt', 'w+') as f:
        f.write(f'this is line {k}\n')
```

```python
# 請先自行新增file_a.txt空檔
for k in range(3):
    with open('file_a.txt', 'a+') as f:
        f.write(f'this is line {k}\n')
```

### B. 開檔後先寫入再讀取檔案內容 <a href="#kai-dang-hou-xian-xie-ru-zai-du-qu-dang-an-nei-rong" id="kai-dang-hou-xian-xie-ru-zai-du-qu-dang-an-nei-rong"></a>

【試試看看】

> 下列三種個`.txt`檔都請先事先設為：

```python
line: 70
line: 80 
line: 90 
line: 20
line: 10
line: 00
```

再開始測試下列三種讀寫檔案方式：<br>

```python
with open('file_r.txt', 'r+') as f:
    for k in range(3):
        f.write(f'line: {k} \n')
    f.seek(0) # 回到檔案第一列第一行
    print(f.read())
```

```python
with open('file_w.txt', 'w+') as f:
    for k in range(3):
        f.write(f'line: {k} \n')
    f.seek(0) # 回到檔案第一列第一行
    print(f.read())
```

```python
with open('file_a.txt', 'a+') as f:
    for k in range(3):
        f.write(f'line: {k} \n')
    f.seek(0) # 回到檔案第一列第一行
    print(f.read())
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://simplife.gitbook.io/python/xin-shou-cun/10.-dang-an-du-xie.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
