从零学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”,有大神能给解惑一下不


猜你喜欢
- 本文实例讲述了php获取给定日期相差天数的方法。分享给大家供大家参考,具体如下:方法一:<?phpfunction count_day
- 最近真的喜欢上了用xheditor这个在线编辑器,但是美中不足的是我发现它暂时还不能取代FCKeditor,因为没有在线上传功能啊!当然,F
- 软件版本:python 3.7.2selenium 3.141.0pycharm 2018.3.5具体实现流程如下,废话不多说,直接上代码:
- 关于 *args与**args的用法*args 和 **kwargs主要用于函数定义,你可以将不定数量的参数传递给某个函数。*args*ar
- 以前看过几个JS代码格式的,自己也来写了一个,呵呵,优点是可以处理超长的 JS 而不会死机.........IE Only运行代码框<
- 本文实例讲述了Smarty实现页面静态化(生成HTML)的方法。分享给大家供大家参考,具体如下:为了减少数据库读取次数,某些内容不经常被更改
- MySQL通常使用GROUPBY(本质上是排序动作)完成DISTINCT操作,如果DISTINCT操作和ORDERBY操作组合使用,通常会用
- 使用filter函数,实现一个条件判断函数即可。比如想过滤掉字符串数组中某个敏感词,示范代码如下:#filter out some unwa
- 一、pytest.ini说明pytest.ini是pytest的全局配置文件,一般放在项目的根目录下固定的配置文件(pytest.ini),
- MySQL数据库在升级到5.7版本后,和之前的版本有些不一样,没有data文件夹,我们都知道MySQL数据库文件是保存在data文件夹中的,
- 前言;python由于它动态解释性语言的特性,跑起代码来相比java、c++要慢很多,尤其在做科学计算的时候,十亿百亿级别的运算,让pyth
- temp.html<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transiti
- 快速掌握 Mysql数据库对文件操作的封装在查看Mysql对文件的操作中,它在不同的操作系统上对文件的操作,除了使用标准C运行库函数,包括o
- 如果你是一个pandas初学者,那么不知道你会不会像我一样。在学用列表或者数组创建DataFrame时理不清怎样用数据生成以及想要形状的的D
- 本文实例讲述了js实现的全国省市二级联动下拉选择菜单。分享给大家供大家参考。具体如下:运行效果截图如下:具体代码如下:<!DOCTYP
- 一、构造dataframeimport pandas as pdimport numpy as npdf=pd.DataFrame(np.a
- 1、先看看什么是 iterable 对象以内置的max函数为例子,查看其doc:>>> print max.__doc__
- 一、环境搭建1、安装python+pycharm软件 。python安装网址官网:https://www.python.org/about/
- -- 任意的测试表 代码如下:CREATE TABLE test_delete( name varchar(10), value INT )
- Python中try块可以捕获测试代码块中的错误。except块可以处理错误。finally块可以执行代码,而不管try-和except块的