r:可读
w:可写
一、将文件中的内容读出来
下面三个例子为读取一个文本文件
1:文件找不到会引发FileNotFoundError,指定了未知的编码会引发LookupError,而如果读取文件时无法按指定方式解码会引发UnicodeDecodeError
2:最后我们使用finally代码块来关闭打开的文件,释放掉程序中获取的外部资源,由于finally块的代码不论程序正常还是异常都会执行到(甚至是调用了sys模块的exit函数退出Python环境,finally块都会被执行,因为exit函数实质上是引发了SystemExit异常),因此我们通常把finally块称为“总是执行代码块”,它最适合用来做释放外部资源的操作。如果不愿意在finally代码块中关闭文件对象释放资源,也可以使用上下文语法,通过with关键字指定文件对象的上下文环境并在离开上下文环境时自动释放文件资源,
f = None
try:
f = open('fg.txt','r',encoding='utf-8')
print(f.read())
except FileNotFoundError:
print('文件无法找到')
except LookupError:
print('未知编码')
except UnicodeDecodeError:
print('文件解码错误')
finally: #总是执行,释放外部资源
if f:
f.close()
def main():
try: #with:自动释放资源
with open('fg.txt','r',encoding='utf-8') as f:
print(f.read())
except FileNotFoundError:
print('无法找到文件')
except LookupError:
print('指定了未知编码')
except UnicodeDecodeError:
print('文件编码错误')
import time
def main():
#一次读取所有内容
with open('fg.txt','r',encoding='utf-8') as f:
print(f.read())
#逐行读取内容
with open('fg.txt',mode='r',encoding='utf-8') as f:
for line in f:
print(line,end='')
time.sleep(0.5)
print()
#逐行读取到列表中
with open('fg.txt',encoding='utf-8') as f:
lines = f.readlines()
print(lines)
``
二、将数据写入文件中
例子1:找出1到10000的素数,并分别写入到3个文本中
from math import sqrt
def is_prime(n):
assert n > 0 #判断函数
for factor in range(2,int(sqrt(n)) + 1):
if n % factor == 0:
return False
return True if n != 1 else False
def main():
filenames = (‘a.txt’,‘b.txt’,‘c.txt’)
fs_list = []
try:
for filename in filenames:
fs_list.append(open(filename,‘w’,encoding=‘utf-8’))
for number in range(1,10000):
if is_prime(number):
if number < 100:
fs_list[0].write(str(number) + ‘\n’)
elif number < 1000:
fs_list[1].write(str(number) + ‘\n’)
else:
fs_list[2].write(str(number) + ‘\n’)
except IOError as ex:
print(ex)
print(‘写文件发生错误’)
finally:
for fs in fs_list:
fs.close()
print(‘操作完成’)
例子2:
#读取二进制图片,并复制
def main():
try:
with open(‘mat.png’,‘rb’) as fs1:
data = fs1.read()
print(type(data))
with open(‘mat.jpg’,‘wb’) as fs2:
fs2.write(data)
except FileNotFoundError as e:
print(‘无法打开’)
except IOError as e:
print(‘读取出错’)
print(‘执行结束’)
以JSON格式保存
import json
def main():
mydict = {
‘name’: ‘骆昊’,
‘age’: 38,
‘qq’: 957658,
‘friends’: [‘王大锤’, ‘白元芳’],
‘cars’: [
{‘brand’: ‘BYD’, ‘max_speed’: 180},
{‘brand’: ‘Audi’, ‘max_speed’: 280},
{‘brand’: ‘Benz’, ‘max_speed’: 320}
]
}
try:
with open(‘data.json’,‘w’,encoding=‘utf-8’) as fs:
json.dump(mydict,fs)
except IOError as e:
print(e)
print(‘保存成功’)