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)#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
Head First Python-Python中与文件相关的操作-读、处理、写的更多相关文章
- Python中的文件和目录操作实现
Python中的文件和目录操作实现 对于文件和目录的处理,虽然可以通过操作系统命令来完成,但是Python语言为了便于开发人员以编程的方式处理相关工作,提供了许多处理文件和目录的内置函数.重要的是,这 ...
- C++ STL中Map的相关排序操作:按Key排序和按Value排序 - 编程小径 - 博客频道 - CSDN.NET
C++ STL中Map的相关排序操作:按Key排序和按Value排序 - 编程小径 - 博客频道 - CSDN.NET C++ STL中Map的相关排序操作:按Key排序和按Value排序 分类: C ...
- python中 对文件的读写操作 以及如何边写入 边保存flush()
转自:https://blog.csdn.net/t8116189520/article/details/78854708 首先 python中打开文件大致常用的几类如下: 1.写入文件write # ...
- 洗礼灵魂,修炼python(19)--文件I/O操作,linecache,fileinput模块
文件I/O操作 1.什么是文件I/O操作 首先I/O(input/output),即输入/输出端口,然后文件,大家应该都是是什么,一个数据,一个txt或者html文档就是一个文件.文件操作就是对文件进 ...
- linux中Makefile文件相关内容
第一章.概述什么是makefile?或许很多Winodws的程序员都不知道这个东西,因为那些Windows的IDE都为你做了这个工作,但我觉得要作一个好的和professional(专业)的程序员,m ...
- python文本操作—读、写
文本文件存储的数据有很多,我们需要把这些文本里的内容读出来,然后在浏览器上面显示. 1.读取整个文本文件 格式: with open(路径) as 变量: 变量.read() 关键字with作用:在不 ...
- PHP文件相关的操作函数——目录操作
1.有关文件类型的函数 PHP是以UNIX的文件系统为模型的,因此在Windows系统中我们只能获得“file”.“dir”或者“unknown”三种文件类型.而在UNIX系统中,我们可以获得“blo ...
- Sharepoint中有关文件夹的操作
1.GetItemsWithUniquePermissions根据返回数量和是否返回文件夹获取唯一权限的列表项集合 对于SharePoint对象模型中SPList的GetItemsWithUnique ...
- R语言文件相关的操作
1. 文件系统介绍 R语言对文件系统的操作,包括文件操作和目录操作,函数API都定义在base包中. 2. 目录操作 2.1 查看目录 查看当前目录下的子目录. # 启动R程序 ~ R # 当前的目录 ...
随机推荐
- POJ 2318 TOYS (叉积+二分)
题目: Description Calculate the number of toys that land in each bin of a partitioned toy box. Mom and ...
- hiho 1097 最小生成树一·Prim算法 (最小生成树)
题目: 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 最近,小Hi很喜欢玩的一款游戏模拟城市开放出了新Mod,在这个Mod中,玩家可以拥有不止一个城市了! 但是,问 ...
- Web应用程序的敏感信息-隐藏目录和文件
Web应用程序的敏感信息-隐藏目录和文件 0x1.场景 Web应用程序根文件夹中可能存在大量隐藏信息:源代码版本系统文件夹和文件(.git,.gitignore,.svn),项目配置文件(.npmrc ...
- Linux centos系统安装后的基本配置,Linux命令
一.centos系统安装后的基本配置 .常用软件安装 yum install -y bash-completion vim lrzsz wget expect net-tools nc nmap tr ...
- cocos2dx-lua 圆角矩形 圆角图片 drawNode
使用的官方类是:drawNode 函数是:drawNode:drawPolygon() C++函数的参数说明: //画多边形,verts为点集,count为点数,fillColor为填充颜色,bord ...
- python下的异常处理
一.什么是异常 程序运行过程中错误发生的信号.(如果运行时产生的异常,程序不处理就会被抛出,随之会造成程序终止) 二.异常的种类 首先,异常主要分为语法错误.逻辑错误两种类型 语法错误会在程序还没有执 ...
- 网络流24题——圆桌问题 luogu 3254
题目传送门:这里 这是网络流24题里最简单的一道,我们从这里开始 虽然是网络流24题之一,但可以不用网络流... 本题采用贪心即可 有一个很显然的思想:在分配每一组时,我们都应当优先分配给当前可容纳人 ...
- Eclipse IDE 添加jar包到Java工程中
操作系统:Windows 10 x64 工具1:Eclipse Java EE IDE for Web Developers. Version: Photon Release (4.8.0) 在Pac ...
- Excel 恢复默认行高、列宽
操作系统:Windows 10 x64 工具1:Excel 乱糟糟的! 选中需要调整的区域,选择菜单:开始 > 格式 > 自动调整行高 选中需要调整的区域,选择菜单:开始 > 格式 ...
- 微信小程序换皮肤,动态切换菜单栏和导航栏的样式,动态修改TabBar和NavigationBar
在做微信小程序换皮肤的时候,需要动态修改菜单栏(TabBar)和导航栏(NavigationBar) 但是在小程序中它们的样式是写在app.json里面,而且app.json是静态编译,运行时哪怕你修 ...