一、读写模式
‘r’:只读。该文件必须已存在。
‘r+’:可读可写。该文件必须已存在,写为追加在文件内容末尾。如需任意位置写,需移动光标。
‘rb’:表示以二进制方式读取文件。该文件必须已存在。
‘w’:只写。打开即默认创建一个新文件,如果文件已存在,则覆盖写(即文件内原始数据会被新写入的数据清空覆盖)。
‘w+’:写读。打开创建新文件并写入数据,如果文件已存在,则覆盖写。
‘wb’:表示以二进制写方式打开,只能写文件, 如果文件不存在,创建该文件;如果文件已存在,则覆盖写。
‘a’:追加写。若打开的是已有文件则直接对已有文件操作,若打开文件不存在则创建新文件,只能执行写(追加在后面),不能读。
‘a+’:追加读写。打开文件方式与写入方式和'a'一样,但是可以读。需注意的是若刚用‘a+’打开一个文件,一般不能直接读取,因为此时光标已经是文件末尾,除非你把光标移动到初始位置或任意非末尾的位置。
二、文件读写
# 以只读模式打开文件
file = open('test.txt', 'r')
# 以写入模式打开文件,覆盖原内容(不存在则创建)
file = open('test.txt', 'w')
# 以追加模式打开文件,从文件末尾开始(不存在则创建)
file = open('test.txt', 'a')
# 以二进制模式打开文件
file = open('test.jpg', 'rb')
一个读取txt的示例:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def readfile():
try:
with open('test.txt', 'r') as file:
#file.read() # 读取全部内容
'''
# 读取全部行
lines = file.readlines()
for line in lines:
print(line)
'''
line = file.readline()
while line:
print(line)
line = file.readline()
except FileNotFoundError:
print('文件不存在!')
except PermissionError:
print('无权限访问文件!')
except Exception as e:
print(f'发生未知错误:{e}')
finally:
file.close()
if __name__ == '__main__':
readfile()
三、内存I/O
除了读写文件之外,在应用场景中,我们还需要使用read wirte的方式操作内存字符串和字符数组。所以需要引入StringIO和BytesIO的概念。StringIO和上面的txt文件读写,可以称作文本IO
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import io
def writefile():
with open('E:\\test.txt', 'a') as file:
file.write("write some text. \n this is a new line.\n")
def readfile():
try:
with open('E:\\test.txt', 'r') as file:
#file.read() # 读取全部内容
'''
# 读取全部行
lines = file.readlines()
for line in lines:
print(line)
'''
line = file.readline()
while line:
print(line)
line = file.readline()
except FileNotFoundError:
print('文件不存在!')
except PermissionError:
print('无权限访问文件!')
except Exception as e:
print(f'发生未知错误:{e}')
finally:
file.close()
def stringIO_demo():
f = io.StringIO("some initial text data")
#从头开始写,覆盖原来的数据
f.write('hello world!')
#移动光标至末尾,以便追加数据
f.seek(0, io.SEEK_END)
f.write(' append to the end')
print(f.getvalue())
def bytesIO_demo():
f = io.BytesIO(b"some initial binary data: \x00\x01")
f.write('测试'.encode('utf-8'))
print(f.getvalue())
if __name__ == '__main__':
writefile()
readfile()
stringIO_demo()
bytesIO_demo()
如过程没有异常,执行输出如下:
this is a new line.
write some text.
this is a new line.
hello world! text dataappend to the end
b'\xe6\xb5\x8b\xe8\xaf\x95nitial binary data: \x00\x01'
四、INI文件读取
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import configparser
#让配置具备默认值
class MyIniParser(configparser.ConfigParser):
def __init__(self):
return super().__init__()
def getEx(self,section,option,default):
try:
if isinstance(default, bool):
return configparser.ConfigParser.getboolean(self, section, option)
elif isinstance(default, int):
return configparser.ConfigParser.getint(self, section, option)
elif # isinstance(default, str):
return configparser.ConfigParser.get(self, section, option)
#其他数据类型需补充,此处仅操作测试使用!!!!!!
except (configparser.NoSectionError, configparser.NoOptionError):
return default
def readIni():
config = MyIniParser()
print (config.read('E:\\config.ini'))
print ("Sections : ", config.sections())
print ("Installation Library : ", config.getEx('installation','library',"test.dll"))
print ("Log Errors debugged ? : ", config.getEx('debug','log_errors',False))
print ("Port Server : ", config.getEx('server','port',1234))
print ("Worker Server : ", config.getEx('server','nworkers',15))
if __name__ == '__main__':
readIni()
五、JSON文件读取
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
strs = '{"姓名": "张三", "爱好": ["足球", "看电影", "徒步"]}'
data = json.loads(strs)
print(data['姓名'])
print(data['爱好'])
print('-------------------------------------------')
#.encode('utf-8').decode('utf-8')
print(json.dumps(data, ensure_ascii=False, indent=4))
结果输出:
张三
['足球', '看电影', '徒步']
-------------------------------------------
{
"姓名": "张三",
"爱好": [
"足球",
"看电影",
"徒步"
]
}