Python学习_从文件读取数据和保存数据
运用Python中的内置函数open()与文件进行交互
在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()方法回到文件起始位置
0
>>> 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”
Python学习_从文件读取数据和保存数据的更多相关文章
- python学习_数据处理编程实例(二)
		
在上一节python学习_数据处理编程实例(二)的基础上数据发生了变化,文件中除了学生的成绩外,新增了学生姓名和出生年月的信息,因此将要成变成:分别根据姓名输出每个学生的无重复的前三个最好成绩和出生年 ...
 - Python 3.6 抓取微博m站数据
		
Python 3.6 抓取微博m站数据 2019.05.01 更新内容 containerid 可以通过 "107603" + user_id 组装得到,无需请求个人信息获取: 优 ...
 - Python测试开发-创建模态框及保存数据
		
Python测试开发-创建模态框及保存数据 原创: fin 测试开发社区 前天 什么是模态框? 模态框是指的在覆盖在父窗体上的子窗体.可用来做交互,我们经常会看到模态框用来登录.确定等等,到底是怎 ...
 - Python实例之抓取淘宝商品数据(json型数据)并保存为TXT
		
本实例实现了抓取淘宝网中以‘python’为关键字的搜索结果,经详细查看数据存储于html文档中的js脚本中,数据类型为JSON 具体实现代码如下: import requests import re ...
 - 【转】Python爬虫:抓取新浪新闻数据
		
案例一 抓取对象: 新浪国内新闻(http://news.sina.com.cn/china/),该列表中的标题名称.时间.链接. 完整代码: from bs4 import BeautifulSou ...
 - Python小爬虫——抓取豆瓣电影Top250数据
		
python抓取豆瓣电影Top250数据 1.豆瓣地址:https://movie.douban.com/top250?start=25&filter= 2.主要流程是抓取该网址下的Top25 ...
 - Python爬虫:抓取新浪新闻数据
		
案例一 抓取对象: 新浪国内新闻(http://news.sina.com.cn/china/),该列表中的标题名称.时间.链接. 完整代码: from bs4 import BeautifulSou ...
 - Android开发学习---android下的数据持久化,保存数据到rom文件,android_data目录下文件访问的权限控制
		
一.需求 做一个类似QQ登录似的app,将数据写到ROM文件里,并对数据进行回显. 二.截图 登录界面: 文件浏览器,查看文件的保存路径:/data/data/com.amos.datasave/fi ...
 - python学习笔记:第6天 小数据池和编码转换
		
目录 1. id 和 == 2. 小数据池 3. 编码和解码 1. id 和 == id:id是一个内置的函数,可以查看变量存放的内存地址(实际上不是真正的物理地址,这里暂时这样理解),用于判断是变量 ...
 
随机推荐
- C语言第一节 C语言程序与开发工具
			
开发工具的选择 可以用来写代码的工具:记事本.UltraEdit.Vim.Xcode等 选择Xcode的原因:苹果官方提供的开发利器.简化开发过程.有高亮显示功能 使用Xcode新建一个C程序的源代码 ...
 - Stupid Tower Defense
			
Problem Description FSF is addicted to a stupid tower defense game. The goal of tower defense games ...
 - TCP/IP协议原理与应用笔记18:构成子网和超网
			
1. 引言: (1)类别IP编址(Classful IP)的缺陷 • 固定的3种IP网络规模 C类地址:少于255台主机的网络 B类地址:介于255~65535台主机的网络 ...
 - 通用超级强大的基于Oracle数据库的代码生成器
			
项目中使用了Oracle数据库,命名基本规范为表名和字段名全部大写,用下划线分割各个单词: 如“BASE_USER_LOGON_EXTEND”这个表表示用户登录的扩展表. 基于这个规范,通用权限管理系 ...
 - [Android]Log打印
			
package com.lurencun.android.system; import android.util.Log; public class ExLog { static final Stri ...
 - CF A and B and Chess
			
A and B and Chess time limit per test 1 second memory limit per test 256 megabytes input standard in ...
 - Mysql打开日志信息
			
还可参考博客:http://pangge.blog.51cto.com/6013757/1319304 1)怎么查看mysql是否启用了日志 mysql>show variables like ...
 - [改善Java代码]警惕泛型是不能协变和逆变的
			
什么叫做协变(covariance)和逆变(contravariance)? 在变成语言的类型框架中,协变和逆变是指宽类型和窄类型在某种情况下(如参数,泛型,返回值)替换或交换的特性,简单的说,协变是 ...
 - 【线性结构上的动态规划】UVa 11584 - Partitioning by Palindromes
			
回文串问题.给出一个字符串,问最少可以划分为多少个字符串子串. 对于判断是否为回文串,对于不是很长的字符串,可以采取直接暴力,即从两边向中间收缩判断字符相等. bool is_pali(int l, ...
 - Networking - Ethernet II 帧
			
Ethernet II 帧格式 DA SA Type Playload FCS DA(Destination Address): 该字段有 6 个字节,表示目的 MAC 地址. SA(Source A ...