User: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)  #废物回收