1. 文件基本概念
文件:存儲在計算機上的數據集合,Python 通過文件對象來操作文件。
文件類型:
-
文本文件:由字符組成,如 .txt, .py
-
二進制文件:由字節組成,如 .jpg, .mp3
2. 文件打開與關閉
2.1 open() 函數
# 打開文件的基本語法
file = open('example.txt', 'r') # 'r'表示讀取模式
file.close() # 關閉文件
2.2 文件打開模式
模式 | 描述 |
---|---|
'r' | 只讀(默認) |
'w' | 寫入(會覆蓋) |
'a' | 追加 |
'x' | 創建新文件 |
'b' | 二進制模式 |
't' | 文本模式(默認) |
'+' | 讀寫模式 |
# 使用 with 語句自動管理文件(推薦)
with open('example.txt', 'r') as file:content = file.read() # 讀取文件內容
# 離開 with 塊后文件自動關閉
3. 文件讀取方法
3.1 讀取整個文件
with open('example.txt', 'r') as file:content = file.read() # 讀取全部內容為字符串print(content)
3.2 逐行讀取
# 方法1:使用 readline()
with open('example.txt', 'r') as file:line = file.readline() # 讀取一行while line:print(line.strip()) # strip() 去除換行符line = file.readline()# 方法2:使用 readlines()
with open('example.txt', 'r') as file:lines = file.readlines() # 讀取所有行到列表for line in lines:print(line.strip())# 方法3:直接迭代文件對象(推薦)
with open('example.txt', 'r') as file:for line in file: # 逐行迭代print(line.strip())
4. 文件寫入方法
4.1 寫入字符串
# 寫入模式(會覆蓋原文件)
with open('output.txt', 'w') as file:file.write("Hello, World!\n") # 寫入字符串file.write("This is a new line.\n")# 追加模式
with open('output.txt', 'a') as file:file.write("This line will be appended.\n")
4.2 寫入多行
lines = ["First line\n", "Second line\n", "Third line\n"]
with open('output.txt', 'w') as file:file.writelines(lines) # 寫入多行
5. 文件位置操作
with open('example.txt', 'rb') as file: # 二進制模式才能使用 seek()print(file.tell()) # 獲取當前文件位置(字節偏移量)content = file.read(10) # 讀取10個字節print(content)file.seek(5) # 移動到第5個字節print(file.read(5)) # 讀取接下來的5個字節
6. 二進制文件操作
# 讀取二進制文件
with open('image.jpg', 'rb') as file:data = file.read() # 讀取二進制數據# 寫入二進制文件
with open('copy.jpg', 'wb') as file:file.write(data) # 寫入二進制數據
7. 文件與目錄操作(os 模塊)
import os# 檢查文件/目錄是否存在
print(os.path.exists('example.txt')) # True/False# 獲取文件大小
print(os.path.getsize('example.txt')) # 字節數# 重命名文件
os.rename('old.txt', 'new.txt')# 刪除文件
os.remove('file_to_delete.txt')# 目錄操作
os.mkdir('new_dir') # 創建目錄
os.rmdir('empty_dir') # 刪除空目錄
8. 文件路徑操作(os.path 模塊)
import os.path# 獲取絕對路徑
print(os.path.abspath('example.txt'))# 檢查是否為文件/目錄
print(os.path.isfile('example.txt')) # True
print(os.path.isdir('example.txt')) # False# 路徑拼接
print(os.path.join('folder', 'subfolder', 'file.txt'))# 獲取文件名和擴展名
print(os.path.basename('/path/to/file.txt')) # 'file.txt'
print(os.path.splitext('file.txt')) # ('file', '.txt')
9. 臨時文件(tempfile 模塊)
import tempfile# 創建臨時文件
with tempfile.NamedTemporaryFile(delete=False) as temp_file:temp_file.write(b"Temporary data") # 寫入臨時數據temp_path = temp_file.name # 獲取臨時文件路徑print(f"臨時文件路徑: {temp_path}")# 臨時文件會在關閉后自動刪除(除非設置 delete=False)
10. 文件編碼處理
# 指定編碼方式(推薦)
with open('example.txt', 'r', encoding='utf-8') as file:content = file.read()# 處理編碼錯誤
try:with open('example.txt', 'r', encoding='utf-8') as file:content = file.read()
except UnicodeDecodeError:print("文件編碼不匹配!")# 寫入時指定編碼
with open('output.txt', 'w', encoding='utf-8') as file:file.write("包含中文的內容")
11. CSV 文件處理
import csv# 讀取CSV文件
with open('data.csv', 'r', encoding='utf-8') as file:reader = csv.reader(file)for row in reader:print(row) # 每行是一個列表# 寫入CSV文件
data = [['Name', 'Age'], ['Alice', 25], ['Bob', 30]]
with open('output.csv', 'w', encoding='utf-8', newline='') as file:writer = csv.writer(file)writer.writerows(data) # 寫入多行
12. JSON 文件處理
import json# 寫入JSON文件
data = {'name': 'Alice', 'age': 25, 'skills': ['Python', 'Java']}
with open('data.json', 'w', encoding='utf-8') as file:json.dump(data, file, indent=4) # indent參數美化輸出# 讀取JSON文件
with open('data.json', 'r', encoding='utf-8') as file:loaded_data = json.load(file)print(loaded_data['name']) # Alice
13. 文件操作最佳實踐
-
始終使用?
with
?語句管理文件資源 -
明確指定文件編碼(特別是處理文本時)
-
處理大文件時使用迭代方式而非一次性讀取
-
檢查文件/目錄是否存在再進行操作
-
合理處理文件操作可能引發的異常
-
使用?
os.path
?進行路徑操作而非字符串拼接 -
敏感操作前對數據做好備份
14. 常見文件操作異常處理
try:with open('nonexistent.txt', 'r') as file:content = file.read()
except FileNotFoundError:print("文件不存在!")
except PermissionError:print("沒有文件訪問權限!")
except IOError as e:print(f"文件操作錯誤: {e}")
finally:print("操作結束")
如果您覺得本文章對您有幫助,別忘了點贊、收藏加關注,更多干貨內容將持續發布,您的支持就是作者更新最大的動力。本專欄將持續更新,有任何問題都可以在評論區討論