head first python读书笔记(十)

本文介绍了Python中处理文件的几种方法,包括使用try-finally确保文件正确关闭,利用字符串格式化输出错误信息,以及with语句简化文件操作。此外,还探讨了pickle模块的基本使用方法及其常见问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

读了三个程序,楼主发现,还是自己的基本功不够扎实,很多东西都不会解决,所以,楼主又回归了head first python。今天楼主从网上看到了一个非常好的博客:http://blog.sina.com.cn/s/blog_620987bf0102vkdv.html。 博客的主人看得出是一个注重积累的人,楼主很是欣赏,而且,楼主找到了一个提高进度的方法。楼主看了一下,第七章往后大部分是网站和应用开发,楼主应该不会去看了,所以还剩下100页。楼主决定,10页一小组,20页一大组。第一遍,先把大组中的大体内容看一下,第二遍,把小组的细节看一下,第三遍,把小组的程序实现,第四遍,把大组的内容写成读书笔记。以读书笔记替代教程博客,应该能省下楼主不少时间。楼主加油~~~

******************************华丽丽的分割线********************************************

1、用finally来避免由于文件缺失而造成的无法关闭的错误:

>>> try:
data=open('missing.txt')
print(data.readline(),end='')
except IOError:
print('File error')
finally:
if 'data' in locals():
data.close()

还要注意一点,if 'data' in locals(): 的用法,是用来判断文件是否在本地的


2、except的一点小改动,注意str的用法,这样就可以按照意愿输出错误

>>> try:
data=open('missing.txt')
print(data.readline(),end='')
except IOError as err:
print('File error:'+str(err))
finally:
if 'data' in locals():
data.close()



File error:[Errno 2] No such file or directory: 'missing.txt'


3、with的用法:python自动关闭文件

>>> try:
with open('its.txt','w') as data:
print("It's ...",file=data)
except IOError as err:
print('File error:'+str(err))


with用法示例:问题是man是如何被赋值的呢?

>>> try:
with open('man_data.txt','w') as man_file:
print(man,file=man_file)
with open('other_data.txt','w') as other_file:
print(other,file=other_file)
except IOError as err:
print('File error:' + str(err))

with用法示例2,把所有文件的打开用一个with实现,注意open中间用‘,’且with最后用‘:’!!!!!
>>> try:
with open('man_data.txt','w') as man_file,open('other_data.txt','w') as other_file:
print(man,file=man_file)
print(other,file=other_file)
except IOError as err:
print('File error:' + str(err))

with打开文本文件,并显示其中的一行:

>>> with open('sketch.txt') as st:
print(st.readline())

Man: Is this the right room for an argument?


4、pickle.dump和load的用法,按照head first python写的,不知道为什么出了这两个问题。

>>> try:
with open('sketch.txt','wb') as st_file:
pickle.dump(st,st_file)
except IOError as err:
print('File error:'+ str(err))
except pickle.PickleError as perr:
print('Pickling error:' + str(perr))



Traceback (most recent call last):
  File "<pyshell#125>", line 3, in <module>
    pickle.dump(st,st_file)
TypeError: cannot serialize '_io.BufferedWriter' object


>>> try:
with open('sketch.txt','rb') as st_file:
st=pickle.load(st_file)
except IOError as err:
print('File error:'+str(err))
except pickle.PickleError as perr:
print('Pickling error:'+str(perr))



Traceback (most recent call last):
  File "<pyshell#133>", line 3, in <module>
    st=pickle.load(st_file)
EOFError: Ran out of input

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值