Head First Python-Python中与文件相关的操作-读、处理、写
最近在看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)#1def printList(movies,intent=False,t=0):for i in movies:if isinstance(i , list): #isinstance检查一个标识符是否指示某个指定类型的数据对象# for j in i:printList(i,intent,t+1)#增加一层嵌套制表符加1else: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:passdata.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 sysdef 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:passdata.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
转载于:https://www.cnblogs.com/hoaprox/p/9568935.html
Head First Python-Python中与文件相关的操作-读、处理、写相关推荐
- python操作目录_详解python中的文件与目录操作
详解python中的文件与目录操作 一 获得当前路径 1.代码1 >>>import os >>>print('Current directory is ',os. ...
- python显示目录中的文件_Python中的文件和目录操作实现
Python中的文件和目录操作实现 对于文件和目录的处理,虽然可以通过操作系统命令来完成,但是Python语言为了便于开发人员以编程的方式处理相关工作,提供了许多处理文件和目录的内置函数.重要的是,这 ...
- Python中的文件及目录操作
Python中的文件及目录操作 在变量.序列和对象中存储的数据是暂时的,程序结束后就会丢失.为了能够长时间地保存程序中的数据,需要将程序中的数据保存到磁盘文件中.Python提供了内置的文件对象和对文 ...
- python的错误 File E:/Python 的代码大大/文件的读写操作.py, line 1 SyntaxError: Non-UTF-8 code starting with '\xcf
错误: File "E:/Python 的代码大大/文件的读写操作.py", line 1 SyntaxError: Non-UTF-8 code starting with '\ ...
- Ksh if判断中与文件相关的选项整理
整理了下Ksh中if判断中与文件相关的各种选项 选项 描述 -a File 如果指定的文件是指向另一个存在的文件的符号链接,则为True. -b File 如果指定的文件存在并且是块特殊文件,则为Tr ...
- 【新星计划】 Python的txt文本操作-读、写
Python的txt文本操作-读.写 读取txt文本 python常用的读取文件函数有三种read().readline().readlines() 以读取上述txt为例,看一下三者的区别 read( ...
- Boost:与gz文件相关的操作实例
Boost:与gz文件相关的操作实例 实现功能 C++实现代码 实现功能 与gz文件相关的操作实例,打开,关闭,读写. C++实现代码 #include "zstream.h" # ...
- java 二进制 文件比较_Java中对文件的读写操作之比较
Java 中对文件的读写操作之比较 作者:Jeru Liu 日期:November 29,2000 版本:1.0 纪念在chinaasp积分过一百呕心原创一篇(Java 中对文件的读写操作之比较)拿分 ...
- 嵌入式Linux 的Cramfs 根文件系统配置成可读可写
嵌入式Linux 的Cramfs 根文件系统配置成可读可写 1.概述 从软件角度上看,构建基于ARM技术的linux系统要涉及到引导加载程序.Linux内核.文件系统.用户应用程序几部分的设计.文件 ...
最新文章
- 基于深度学习的位姿估计方法
- h5压缩图片上传 php_一键压缩,图片上传大小不得超过200K?
- 基于RBAC模型的通用权限管理系统的设计(数据模型)的扩展
- 给楠哥准备的入门单片机
- 1.7 编程基础之字符串 33 判断字符串是否为回文 python
- silverlight 一些写法小计
- 关于c语言编写 顺序表 的创建、插入、修改、删除、显示、退出 的程序案例
- android db加载后无法读取任何内容_android性能优化(二)之卡顿优化
- Hibernate继承映射
- [LeetCode]Count and Say
- Mac电脑快捷键效率办公技巧
- Java程序员:java软件工程师中级证
- 怎样批量分析安能物流中含有提前签收的单号
- 《iVX 高仿美团APP制作移动端完整项目》07 会员页制作
- vcm服务器如何修改端口,录音棚里的电动“机器人”-YAMAHA DM1000VCM控制模块设置教程...
- 一款全面超越ps3的国产游戏机
- 百度地图绘制3D棱柱
- Android规范写法
- 配置 VScode 编辑器 (前端篇)
- USI环旭电子推出信用卡大小的SiPSet笔记本电脑主板