---
title: 讀寫檔 - Python 教學
description: 中興大學資訊研究社1101學期程式分享會主題社課
tags: Python
---
###### [Python 教學/](/@NCHUIT/py)
# 讀寫檔
> [name=HuiXillya][time= 110,12,2]
在程式中開啟檔案,眾所周知,電腦儲存資料的方式是以數位(0與1)的方式儲存。
所以我們在對檔案操作的時候,需要注意檔案的編碼。
## 文字檔編碼介紹
### ASCII
一般英數字會使用的編碼,使用一個Byte,若使用正整數表示之,則範圍為0-255
舉例來說
'A' = '0100 0001'
'B' = '0100 0010'
'C' = '0100 0011'
[...更多](https://zh.wikipedia.org/wiki/ASCII)
### Big5
一般來說用在繁體中文,尤其在以前系統中最為常見
現已逐漸不被使用
### utf-8
[編碼方式](https://www.ibm.com/docs/en/db2/11.5?topic=support-unicode-character-encoding)
現今最常見之文字編碼方式,適用於所有語言,當然啦就是用更多位元來表示一個字
## 開啟檔案
[參考這邊](https://docs.python.org/zh-cn/3/library/functions.html?highlight=open#open)
範例
```python=
file_obj = open('test.txt','r')
# test.txt 這部分要填你要開啟的檔案名稱(路徑)
# r 這個是代表你要開啟的方式 r 代表讀檔 w 代表寫檔
```
指定編碼
```python=
file_obj = open('test.txt','r',encoding='utf-8')
```
### 讀檔
#### 讀取指定大小
```python=
file_obj.read(1) #一次讀一個字
```
```python=
file_obj.read() #一次讀完(剩下的)全部
```
#### 讀一行
```python=
file_obj.readlines()
```
### 寫檔
```python=
file_obj = open('test.txt','w',encoding='utf-8')
```
以bytes的形式寫入(多媒體)
```python=
file_obj = open('test.txt','wb',encoding='utf-8') #多加了一個b
```
#### 連續寫入
```python=
file_obj.write(strs) #放入你要寫入的東西(strs),會直接接續在檔案後方
```
多媒體同理,直接丟進去就好
#### 單行寫入
```python=
file_obj.writeline(strs) #與write沒什麼不同,只是多幫你換一行
```
## 儲存檔案(關閉檔案)
```python=
file_obj.close() #關閉檔案並儲存
```
## 另一種方法
```python=
with open('test.txt','r',encoding='utf-8') as file_obj:
file_obj.write('im cool...')
#.
#.
#做完會自動存檔
```