用戶:Xyy23330121/Python/文件處理/open函數的模式

來自維基學院

本文主要討論各種模式下,文件的讀寫行為。因此,這裏不討論字節流,只使用文本流進行測試——如果是字節流,可以類比。

使用 open 函數打開一個內容為 This is a test text file. 的文本文件,並進行讀取和寫入。每次讀取都讀取到文件結束,而每次寫入都是寫入 测试信息

編碼方式為 UTF-8,根據測試結果,可以看出每個漢字在覆蓋字符時,覆蓋 3 個英文字符。

以下是測試結果:

模式 讀取測試 寫入測試
讀取操作成功 讀取結果 操作後的文件信息 寫入操作成功 操作後的文件信息
r 成功 This is a test text file. This is a test text file. 失敗 This is a test text file.
w 失敗     成功 測試信息
a 失敗   This is a test text file. 成功  
r+ 成功 This is a test text file.   成功 測試信息st text file.
w+ 成功     成功 測試信息
a+ 成功   This is a test text file. 成功 This is a test text file.測試信息
模式 連續讀、寫、讀測試
讀取操作成功 讀取結果 寫入操作成功 讀取操作成功 讀取結果 操作後的文件信息
r 成功 This is a test text file. 失敗 成功   This is a test text file.
w 失敗   成功 失敗   測試信息
a 成功   失敗 成功    
r+ 成功 This is a test text file. 成功 成功   This is a test text file.測試信息
w+ 成功   成功 成功   測試信息
a+ 成功   成功 成功   This is a test text file.測試信息
模式 連續寫、讀、寫測試
寫入操作成功 讀取操作成功 讀取結果 寫入操作成功 操作後的文件信息
r 失敗 成功 This is a test text file. 失敗 This is a test text file.
w 成功 失敗   成功 測試信息測試信息
a 成功 失敗   成功  
r+ 成功 成功 st text file. 成功 測試信息st text file.測試信息
w+ 成功 成功   成功 測試信息測試信息
a+ 成功 成功   成功 This is a test text file.測試信息測試信息

測試代碼[編輯 | 編輯原始碼]

#!/usr/bin/python
# -*- coding: utf-8 -*-

import os, shutil

#使用这种方式输出,可以简化我写上面表格的过程。
#其实可以直接输出上面表格对应的 wikitext,但我懒得写更复杂的内容。
prt = lambda x="",e=None: print("||",x, end="\n" if e != None else " ")

#进行一次“读”测试
def rtst(obj):
	try:
		txt = obj.read()
		prt("成功")
		prt(txt)
	except:
		prt("失败")
		prt()

#进行一次“写”测试
def wtst(obj):
	try:
		obj.write("测试信息")
		prt("成功")
	except: prt("失败")

#对一个模式进行完整测试
def test(m):
	print("Mode:",m,"读取测试:")
	shutil.copy2(original, "test.txt")
	with open("test.txt", mode=m, encoding="utf-8") as testobj:
		rtst(testobj)
	with open("test.txt", mode="r", encoding="utf-8") as res:
		prt(res.read(),1)
	os.remove("test.txt")
	
	print("Mode:",m,"写入测试:")
	shutil.copy2(original, "test.txt")
	with open("test.txt", mode=m, encoding="utf-8") as testobj:
		wtst(testobj)
	with open("test.txt", mode="r", encoding="utf-8") as res:
		prt(res.read(),1)
	os.remove("test.txt")
	
	print("Mode:",m,"读写读测试:")
	shutil.copy2(original, "test.txt")
	with open("test.txt", mode=m, encoding="utf-8") as testobj:
		rtst(testobj)
		wtst(testobj)
		rtst(testobj)
	with open("test.txt", mode="r", encoding="utf-8") as res:
		prt(res.read(),1)
	os.remove("test.txt")
	
	print("Mode:",m,"写读写测试:")
	shutil.copy2(original, "test.txt")
	with open("test.txt", mode=m, encoding="utf-8") as testobj:
		wtst(testobj)
		rtst(testobj)
		wtst(testobj)
	with open("test.txt", mode="r", encoding="utf-8") as res:
		prt(res.read(),1)
	os.remove("test.txt")

modes = ["r","w","a","r+","w+","a+"]
original = "0.txt"
os.chdir("D:\\test") #测试前,在 D 盘创建了名为"test"的文件夹。
with open(original, mode="x", encoding="utf-8") as file:
    file.write("This is a test text file.")

for m in modes:
	test(m)

os.remove(original)  #废物回收