最近在看head first python,前面也写了一些笔记,但是基本上没有涉及到一些完整的代码,现在将书中的文件相关操作的代码整理,供以后参考。

主要分为两大部分,读取文件、处理异常,处理文件、存储文件。

0,处理文件

首先介绍后面将会用到的知识点,格式化输出列表;

如果一个列表嵌套多层列表,使用一般的方法来打印无法打印出嵌套的列表。下面的方法只能打印出一层,如果想打印多层怎么办?

movies=['aWith a ','bpopulation of 1060', ['cthe village','dis carpeted with ','eazalea blossoms', ['fwith fast-flowing rivers ','gscattered guesthouses','hadding strokes and splashes to ','ithe natural canvas.']]]

print(movies)
def printList(movies):
for i in movies:
print(i)
print(printList(movies))

下面通过给printList增加参数来控制格式化输出(intent控制是否需要格式化,t用来控制指标表符个数):

movies=['aWith a ','bpopulation of 1060', ['cthe village','dis carpeted with ','eazalea blossoms', ['fwith fast-flowing rivers ','gscattered guesthouses','hadding strokes and splashes to ','ithe natural canvas.']]]

print(movies)#1

def printList(movies,intent=False,t=0):
for i in movies:
if isinstance(i , list): #isinstance检查一个标识符是否指示某个指定类型的数据对象
# for j in i:
printList(i,intent,t+1)#增加一层嵌套制表符加1
else:
if intent:
for j in range(t):
print("\t", end='')
print(i) print(printList(movies,False))#2
print(printList(movies,True,0))#3

输出如下:

1,读取文件

pyhont中使用open来打开一个文件

import  os
if os.path.exists('./temp/sketch.txt'):
data =open('./temp/sketch.txt')
print(data.readline(),end='')
print(data.readline(),end='')
data.seek(0)
for each_line in data:
if not each_line.find(':') == -1:
(role,line_spoken)=each_line.split(':',1)
print(role,end='')
print(' said: ',end='')
print(line_spoken,end='')
data.close()
else:
print('file not exists!!!')

2,处理异常

如果要读取的文件不存在咋办?

data =open('./temp/sketch.txt')
print(data.readline(),end='')
print(data.readline(),end='')
data.seek(0)
for each_line in data:
try:
(role,line_spoken)=each_line.split(':',1)
print(role,end='')
print(' said: ',end='')
print(line_spoken,end='')
except ValueError:
pass
data.close()

我们知道,打开一个文件,读取或者写入结束后要进行关闭。

3,存储文件

保存一个文件:

(1)使用print(),print函数的参数file来定义输出对象,默认输出到屏幕:

man = []
other = []
try:
data=open('./data/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 as err:
print("the datafile is missing..."+str(err)) try:
with open('./temp/man_data.txt','a') as man_data:
print(man, file=man_data)
with open('./temp/other_data.txt','a') as other_data:
print(other, file=other_data)
except IOError as err:
print ('ERROR: '+str(err))

(2)使用pickle(),pickle函数有存文件dump()和读文件load()两个方法,将文件以二进制流的形式存储到本地:

import pickle
import sys def print_lol(the_list,indent=False,level=0,lol=sys.stdout):
for each_item in the_list:
if isinstance(each_item,list):
print_lol(each_item,indent,level+1,lol)
else:
if indent:
for tab_stop in range(level):
print('\t',end='',file=lol)
print(each_item,file=lol) man = []
other = []
try:
data=open('./data/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 as err:
print("the datafile is missing..."+str(err))
#存文件
try:
with open('./temp/man_data.dat','wb') as man_data:
pickle.dump(man,man_data)
with open('./temp/other_data.dat','wb') as other_data:
pickle.dump(other,other_data)
except pickle.PickleError as err:
print ('ERROR: '+str(err))
#读文件
new_man=[]
try:
with open('./temp/man_data.dat','rb') as new_man_file:
new_man=pickle.load(new_man_file)
except IOError as err:
print('IOError: '+str(err))
except pickle.PickleError as perr:
print('PickError: '+ str(perr)) print_lol(new_man)
print(new_man[0])
print(new_man[-1])

代码来源:head first python

最新文章

  1. Arcengine 中,创建色带
  2. OC中的特有语法
  3. Linux设备驱动之中断支持及中断分层
  4. 安装appcan后打开eclipse出错
  5. 线段树的区间更新---A Simple Problem with Integers
  6. unity Android 打包后读取 xml 文件
  7. initWithCoder: 与initWithFrame:
  8. 微信小程序开发之入门篇(熟悉项目结构)
  9. C/C++各种系统开发环境搭建
  10. 在CDockablePane中嵌入CFormView
  11. Azure 基础:Blob Storage
  12. [转载] MapReduce工作原理讲解
  13. [Java]LeetCode278. 第一个错误的版本 | First Bad Version
  14. python栈
  15. 量化交易-外汇交易-MetaTrader5
  16. ZOJ 3781 Paint the Grid Reloaded(DFS连通块缩点+BFS求最短路)
  17. linux -- ubuntu dash bash
  18. bzoj 3339 Rmq Problem / mex
  19. asp.net self host and urlacl(解决UnHandledException Message:拒绝访问的问题)
  20. Aspose.Cells 对excel的使用总结

热门文章

  1. ios9 safari currentTime audio bug
  2. .NET垃圾回收机制(二)
  3. docker报错:Failed to restart docker.service: Unit not found.
  4. 将LibreOffice文档转换为豆瓣日记
  5. OK Titlefasdf asd
  6. Linux安装Tomcat-Nginx-FastDFS-Redis-Solr-集群——【第六集之基本命令使用】
  7. git操作:WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! (警告:远程主机标识已更改!)
  8. 命令行编译C程序
  9. aspnet core运行后台任务
  10. hwy题目选讲