- Python写入文件的基本操作
man = [] other = [] try: data = open('sketch.txt') for each_line in data: try: (role,line_spoken) = each_line.split(':',1) line_spoken = line_spoken.strip() if role = 'Man': man.append(line_spoken) elif role = 'Other Man': other.append(line_spoken) except ValueError: pass data.close() except IOError: print('The datafile is missing!') try: man_file = open('man_data.txt','w') other_file = open('other_data.txt','w') print(man,file=man_file) print(other,file=other_file) except IOError: print('File error.') finally: #使用finally确保close()一定能执行 man_file.close() other_file.close()
- 如何使用异常对象
except IOError as err: #给异常对象起一个名字err print('File error: '+str(err)) #然后用作错误消息的一部分,str() BIF的作用是让异常对象表现为一个字符串
- 用with语句处理文件
由于处理文件是try/except/finally模式相当常用,所以Python提供一个语句来抽象出相关的一些细节。对文件使用with语句时,可以大大减少需要编写的代码量。
普通的try/except/finally模式
try: data = open('its.txt',"w") print("It's...",file=data) except IOError as err: print('File error: '+str(err)) finally: if 'data' in locals(): data.close()
使用with语句
try: with open('its.txt',"w") as data: print("It's...",file=data) except IOError as err: print('File error: '+str(err))
- 使用pickle的通用文件I/O
pickle是Python的一个标准库,它可以保存和加载几乎任何Python对象,包括列表
用dump保存,用load恢复
import pickle #记得导入pickle模块 with open('mydata.pickle','wb') as mysavedata: #'wb'中的b告诉Python以2进制模式打开数据文件 pickle.dump([1,2,'three'],mysavedata) #要保存数据用dump() with open('mydata.pickle','rb') as myrestoredata: a_list = pickle.load(myrestoredata) #使用load()从文件中恢复数据 print(a_list)