[TOC]
<br>
### 獲取文件句柄
在python中,提供內建函數`open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)` 打開一個文件并且返回文件流句柄。
參數說明:
*file* : 文件
*mode* : 文件操作模式,常用的有;‘r’表示打開文件進行讀操作,‘w’表示打開文件進行寫操作,‘a’表示打開文件進行追加寫操作,‘b’表示操作二進制
*encoding* : 編碼格式
open一個文件后,返回一個文件流句柄。通過句柄,可以輕易操作“讀”與“寫”
### 讀文件
```python
with open('users.txt','r') as fp: # 打開文件,fp作為句柄變量
print(fp.read()) # read() 一次性將文件內容讀取到內存
with open('users.txt','r') as fp:
for line in fp.readlines(): # readlines() 一次讀取所有內容并按行返回list
print(line.strip())
with open('users_gbk.txt','r',encoding='gbk') as fp: # 當讀取編碼為‘gbk’的文件時,傳入參數encoding='gbk'
for line in fp: # fp 句柄是一個迭代器,每調用一次,讀取一行,當文件特別大時,建議使用這種方式
print(line.strip())
```
### 寫文件
```python
with open('users2.txt','w') as fp: # 打開文件,fp作為句柄變量
fp.write("Hello World!") # write() 將字符串寫入文件
```
<hr style="margin-top:100px">
:-: 
***微信掃一掃,關注“python測試開發圈”,了解更多測試教程!***
- 前言
- chapter01_開發環境
- chapter02_字符串的使用
- chapter03_列表的使用
- chapter04_字典的使用
- chapter05_數字的使用
- chapter06_元組的使用
- chapter07_集合的使用
- chapter08_輸入輸出
- chapter09_控制流程
- chapter10_實例練習_登錄1
- chapter11_python函數入門
- chapter12_python中的類
- chapter13_輕松玩轉python中的模塊管理
- chapter14_掌握學習新模塊的技巧
- chapter15_通過os模塊與操作系統交互
- chapter16_子進程相關模塊(subprocess)
- chapter17_時間相關模塊(time & datetime)
- chapter18_序列化模塊(json)
- chapter19_加密模塊(hashlib)
- chapter20_文件的讀與寫
- chapter21_階段考核2_登錄
- chapter22_小小算法挑戰(排序&二分法)
- chapter23_用多線程來搞事!
- chapter24_HTTP接口請求(requests)
- chapter25_接口測試框架(pytest)
- chapter26_階段考核3_HTTP接口測試
- chapter27_HTML解析(pyquery)
- chapter28_階段考核4_爬蟲下載網易汽車
- chapter29_python中的那些編碼坑
- chapter30_MySQL數據庫操作
- chapter31 高級特性_迭代器與生成器
- chapter32 高級特性_裝飾器
- chapter33 高級特性_列表處理