从零学python系列之从文件读取和保存数据
发布时间:2021-02-11 01:51:29
在HeadFirstPython网站中下载所有文件,解压后以chapter 3中的“sketch.txt”为例:
新建IDLE会话,首先导入os模块,并将工作目录却换到包含文件“sketch.txt”的文件夹,如C:\\Python33\\HeadFirstPython\\chapter3
>>> import os
>>> os.getcwd() #查看当前工作目录
'C:\\Python33'
>>> os.chdir('C:/Python33/HeadFirstPython/chapter3') #切换包含数据文件的文件夹
>>> os.getcwd() #查看切换后的工作目录
'C:\\Python33\\HeadFirstPython\\chapter3'
打开文件“sketch.txt”,读取并显示前两行:
>>> data=open('sketch.txt')
>>> print(data.readline(),end='')
Man: Is this the right room for an argument?
>>> print(data.readline(),end='')
Other Man: I've told you once.
回到文件起始位置,使用for语句处理文件中的每行,最后关闭文件:
>>> data.seek(0) #使用seek()方法回到文件起始位置
>>> for each_line in data:
print(each_line,end='')
Man: Is this the right room for an argument?
Other Man: I've told you once.
Man: No you haven't!
Other Man: Yes I have.
Man: When?
Other Man: Just now.
Man: No you didn't!
Other Man: Yes I did!
Man: You didn't!
Other Man: I'm telling you, I did!
Man: You did not!
Other Man: Oh I'm sorry, is this a five minute argument, or the full half hour?
Man: Ah! (taking out his wallet and paying) Just the five minutes.
Other Man: Just the five minutes. Thank you.
Other Man: Anyway, I did.
Man: You most certainly did not!
Other Man: Now let's get one thing quite clear: I most definitely told you!
Man: Oh no you didn't!
Other Man: Oh yes I did!
Man: Oh no you didn't!
Other Man: Oh yes I did!
Man: Oh look, this isn't an argument!
(pause)
Other Man: Yes it is!
Man: No it isn't!
(pause)
Man: It's just contradiction!
Other Man: No it isn't!
Man: It IS!
Other Man: It is NOT!
Man: You just contradicted me!
Other Man: No I didn't!
Man: You DID!
Other Man: No no no!
Man: You did just then!
Other Man: Nonsense!
Man: (exasperated) Oh, this is futile!!
(pause)
Other Man: No it isn't!
Man: Yes it is!
>>> data.close()
读取文件后,将不同role对应数据分别保存到列表man和other:
import os
print(os.getcwd())
os.chdir('C:\Python33\HeadFirstPython\chapter3')
man=[] #定义列表man接收Man的内容
other=[] #定义列表other接收Other Man的内容
try:
data=open("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:
print('The datafile is missing!')
print (man)
print (other)
Tips:
使用open()方法打开磁盘文件时,默认的访问模式为r,表示读,不需要特意指定;
要打开一个文件完成写,需要指定模式w,如data=open("sketch.txt","w"),如果该文件已经存在则会清空现有内容;
要追加到一个文件,需要指定模式a,不会清空现有内容;
要打开一个文件完成写和读,且不清空现有内容,需要指定模式w+;
例如,将上例中保存的man和other内容以文件方式保存时,可修改如下:
import os
print(os.getcwd())
os.chdir('C:\Python33\HeadFirstPython\chapter3')
man=[]
other=[]
try:
data=open("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:
print('The datafile is missing!')
try:
man_file=open('man.txt', 'w') #以w模式访问文件man.txt
other_file=open('other.txt','w') #以w模式访问文件other.txt
print (man, file=man_file) #将列表man的内容写到文件中
print (other, file=other_file)
except IOError:
print ('File error')
finally:
man_file.close()
other_file.close()
但是第26行print()为什么会报错?“syntax error while detecting tuple”,有大神能给解惑一下不
猜你喜欢
- 本篇主要将react全家桶的产品非常精炼的提取了核心内容,精华程度堪比精油。各位大人,既然来了,客官您坐,来人,给客官看茶~~redux前言
- 导读:最近数据库经常出现会话阻塞的报警,过一会又会自动消失,昨天晚上恰好发生了一次,于是赶紧进行了查看,不看不知道,一看吓一跳,发现是由da
- 在Web开发中,JavaScript的一个很重要的作用就是对DOM进行操作,可你知道么?对DOM的操作是非常昂贵的,因为这会导致浏览器执行回
- 网页的圆角处理,其实最开始的九宫格的表格处理是挺方便的,只是现在都不用表格布局了,自然就被非法取缔了。呵呵。微软的有VML画圆角,由于只是它
- nofollow标签是Google2005年推出的,目的是尽量减少垃圾链接对搜索引擎的影响。有用过网页制作工具的人都知道,在这些工具里是找不
- 可能有些地方翻译得不好,请见谅在这个冠冕堂皇的标题之下,我想回答一个土方,有人在博客提出很久了。该土方很好的描述了很多图标设计师所面临的典型
- 前言众所周知,python拥有丰富的内置库,还支持众多的第三方库,被称为胶水语言,随机函数库random,就是python自带的标准库,他的
- InnoDB和MyISAM是在使用MySQL最常用的两个表类型,各有优缺点,视具体应用而定。下面是已知的两者之间的差别,仅供参考。1.Inn
- 本文系统的对HTTP Headers进行了简明易懂的阐述,我仅稍作笔记。什么是HTTP HeadersHTTP是“Hypertext Tra
- 如何用Cookie进行登录验证?很简单,看看这两个文件:login.htm请注册登录随风起舞<FORM ACTION=&qu
- 前言Martin(Bob大叔)曾在《代码整洁之道》一书打趣地说:当你的代码在做 Code Review 时,审查者要是愤怒地吼道:“What
- Python 语言的优势在于其功能强大,可以用于网络数据采集、数据分析等各种应用场景。本篇文章将介绍如何使用 Python 获取网络数据、使
- 前言:最近某个时间开始,特别留意了一下Web标准中柱状图,也就是英文中的bar graph的实现。虽然实现方法各异,效果不尽相同,但是总体来
- 上一一节我们讲了while循环,while循环主要用于重复程序的运行,for循环更加倾向于遍历一个项目,即将特定内容(比如一个列表、一个字符
- sort()方法排序列表中的对象,比较使用func(如果给定)。语法以下是sort()方法的语法:list.sort([func
- 以下摘录自 oreilly.JavaScript.The.Definitive.Guide.5th.Edition.Aug.200
- 内容摘要:严格地说,ASP 并不是一门编程语言,所以不存在类这一概念,我们这里说 ASP 类是指 A
- 第一种: <script language="javascript" type="text/javasc
- 内容摘要:通常的,ASP中表单提交的数据一般被写入数据库。然而,如果你想让发送数据更为简便易行,那么,可以将它书写为XML文件格式。这种方式
- 一、基于socket实现的TCP客户端import socket # 建立socket对象# 参数一表示IP地址类型(AF_INE