python文件读写和异常
1,文本文件
-
普通打开
f.open
f.close
def main(): f = None try: f = open('致橡树.txt', 'r', encoding='utf-8') print(f.read()) except FileNotFoundError: print('无法打开指定的文件!') except LookupError: print('指定了未知的编码!') except UnicodeDecodeError: print('读取文件时解码错误!') finally: if f: f.close() if __name__ == '__main__': main()
-
with关键字
with open as f
def main(): try: with open('致橡树.txt', 'r', encoding='utf-8') as f: print(f.read()) except FileNotFoundError: print('无法打开指定的文件!') except LookupError: print('指定了未知的编码!') except UnicodeDecodeError: print('读取文件时解码错误!') if __name__ == '__main__': main()
-
for-in
循环逐行读取或者用readlines
方法将文件按行读取到一个列表容器中import time def main(): # 一次性读取整个文件内容 with open('致橡树.txt', 'r', encoding='utf-8') as f: print(f.read()) # 通过for-in循环逐行读取 with open('致橡树.txt', mode='r') as f: for line in f: print(line, end='') time.sleep(0.5) print() # 读取文件按行读取到列表中 with open('致橡树.txt') as f: lines = f.readlines() print(lines) if __name__ == '__main__': main()
-
写入文本文件
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 num in range(1,10000): if is_prime(num): if num < 100: fs_list[0].write(str(num)+"\n") elif num < 1000: fs_list[1].write(str(num)+"\n") else: fs_list[2].write(str(num)+'\n') except IOError as e: print(e) print("文件写入错误") finally: for fs in fs_list: fs.close() print("操作完成") if __name__ == '__main__': main()
2,二进制文件
def main():
try:
with open('guido.jpg', 'rb') as fs1:
data = fs1.read()
print(type(data)) # <class 'bytes'>
with open('吉多.jpg', 'wb') as fs2:
fs2.write(data)
except FileNotFoundError as e:
print('指定的文件无法打开.')
except IOError as e:
print('读写文件时出现错误.')
print('程序执行结束.')
if __name__ == '__main__':
main()
3,json文件
JSON跟Python中的字典其实是一样一样的,事实上JSON的数据类型和Python的数据类型是很容易找到对应关系的,如下面两张表所示。
JSON | Python |
---|---|
object | dict |
array | list |
string | str |
number (int / real) | int / float |
true / false | True / False |
null | None |
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str | string |
int, float, int- & float-derived Enums | number |
True / False | true / false |
None | null |
我们使用Python中的json模块就可以将字典或列表以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('保存数据完成!')
if __name__ == '__main__':
main()