文件读写和异常处理
-
文件读操作
def main(): f=open('致橡树.txt','r',encoding='utf-8') print(f.read()) f.close() if __name__ == '__main__': main()
-
文件抛出异常的操作
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称为总是执行的函数,可以用来最后释放内存 finally: f.close() if __name__ == '__main__': main()
-
使用with 自动释放空间
def main(): try: #此处可以通过with open as 来自动释放空间 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()
-
按行读取
import time def main(): #一次性读取全部内容 with open('致橡树.txt','r',encoding='utf-8') as f: print(f.read()) #通过for in 按行读取 with open('致橡树.txt', 'r', encoding='utf-8') as f: for line in f: print(line,end='') time.sleep(0.5) print() # 读取文件按行读取到列表中 with open('致橡树.txt', 'r', encoding='utf-8') as f: lines=f.readlines() print(lines) if __name__ == '__main__': main()
-
将1-10000的素数写到3个文档当中
''' 如何将1-9999之间的素数分别写入三个文件中(1-99之间的素数保存在a.txt中,100-999之间的素数保存在b.txt中,1000-9999之间的素数保存在c.txt中)。 ''' from math import sqrt def if_prime(n): ''' 判断是否为素数 :param n: :return: ''' 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 if_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() if __name__ == '__main__': main()
-
二进制复制
#复制二进制文件(图片) def main(): try: with open('小狗.jpeg','rb') as fs1: data=fs1.read() with open('小狗复制.jepg','wb') as fs2: fs2.write(data) except FileNotFoundError as e: print('指定的文件无法打开.') except IOError as e: print('读写文件时出现错误.') print('程序执行结束.') if __name__ == '__main__': main()
-
读写json
#使用json保存列表和字典数据,主要用dump和load 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()