读了三个程序,楼主发现,还是自己的基本功不够扎实,很多东西都不会解决,所以,楼主又回归了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