# Python 檔案操作流程
###### tags: `python`
[參考課程--彭彭](https://www.youtube.com/watch?v=C4OkV6DrVRs&list=PL-g0fdC5RMboYEyt6QS2iLb_1m7QcgfHk&index=13)
操作流程:開啟檔案 >> 讀取或寫入 >> 關閉檔案
## 開啟檔案
語法:
>檔案物件 = open(檔案路徑,mode=開啟模式)
>開啟模式:
>讀取-- r
>寫入-- w
>讀寫-- r+
`
## 讀取檔案
讀取已存在的檔案
```python=
with open("data.txt",mode="w",encoding="utf-8") as file:
file.write("測試中文\n開始")
```
語法:
> 讀取全部文字 :
```python=
with open("data.txt",mode="r",encoding="utf-8") as file:
data=file.read()
print(data) #測試中文 開始
```
檔案物件.read()
> 一次讀取一行:
```python=
for 變數 in 檔案物件:
從檔案依序讀取美航文字到變數中
```
範例:把檔案中的數字資料,一行一行的讀取出來,並計算總和
```python=
#原本檔案 5 \n 3
sum=0
with open("data.txt",mode="r",encoding="utf-8") as file:
for line in file: #一行一行的讀取
sum+=int(line)
print(sum) #8
```
## 讀取、寫入JSON格式
json是以dict型態讀取
json模組
語法:
>import json
>讀取到的資料 = json.load(檔案物件)
>json.dump(修改後的資料,欲寫入更新的檔案)
### 一般
```python=
import json
#從檔案中讀取json資料,放入變數data裡面
with open("config.json",mode="r") as file:
data=json.load(file)
print(data)#字典
print("name",data["name"])
print("version",data["version"])
data["name"]="New name"#修改變數中的資料
with open("config.json",mode="w") as file:#更新json檔案資料
json.dump(data,file)
```
## 寫入檔案
```python=
file = open("data.txt",mode="w") #沒有寫完整路徑,就是指在同一資料夾
file.write("Hello World")
file.close()
```
1. 寫入文字
檔案物件.write(字串)
2. 寫入換行符號
檔案物件.write("範例文字\n")
3. 寫入Json格式
import json
json.dump(要寫入的資料,檔案物件)
## 關閉檔案,釋放資源
基本語法:
檔案物件.close()
## 最常運用的語法
讀取或寫入都可以用,會自動、安全的關閉檔案
**with open(檔案路徑,mode=開啟模式) as 檔案物件:檔案操作**
```python=
with open("data.txt",mode="w",encoding="utf-8") as file:
file.write("測試中文\n開始")
```
不需關閉檔案
## 檔案編碼
encoding="utf-8" 中文編碼
```python=
file = open("data.txt",mode="w",encoding="utf-8")
```