运用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学习_从文件读取数据和保存数据的更多相关文章

  1. python学习_数据处理编程实例(二)

    在上一节python学习_数据处理编程实例(二)的基础上数据发生了变化,文件中除了学生的成绩外,新增了学生姓名和出生年月的信息,因此将要成变成:分别根据姓名输出每个学生的无重复的前三个最好成绩和出生年 ...

  2. Python 3.6 抓取微博m站数据

    Python 3.6 抓取微博m站数据 2019.05.01 更新内容 containerid 可以通过 "107603" + user_id 组装得到,无需请求个人信息获取: 优 ...

  3. Python测试开发-创建模态框及保存数据

    Python测试开发-创建模态框及保存数据 原创: fin  测试开发社区  前天 什么是模态框? 模态框是指的在覆盖在父窗体上的子窗体.可用来做交互,我们经常会看到模态框用来登录.确定等等,到底是怎 ...

  4. Python实例之抓取淘宝商品数据(json型数据)并保存为TXT

    本实例实现了抓取淘宝网中以‘python’为关键字的搜索结果,经详细查看数据存储于html文档中的js脚本中,数据类型为JSON 具体实现代码如下: import requests import re ...

  5. 【转】Python爬虫:抓取新浪新闻数据

    案例一 抓取对象: 新浪国内新闻(http://news.sina.com.cn/china/),该列表中的标题名称.时间.链接. 完整代码: from bs4 import BeautifulSou ...

  6. Python小爬虫——抓取豆瓣电影Top250数据

    python抓取豆瓣电影Top250数据 1.豆瓣地址:https://movie.douban.com/top250?start=25&filter= 2.主要流程是抓取该网址下的Top25 ...

  7. Python爬虫:抓取新浪新闻数据

    案例一 抓取对象: 新浪国内新闻(http://news.sina.com.cn/china/),该列表中的标题名称.时间.链接. 完整代码: from bs4 import BeautifulSou ...

  8. Android开发学习---android下的数据持久化,保存数据到rom文件,android_data目录下文件访问的权限控制

    一.需求 做一个类似QQ登录似的app,将数据写到ROM文件里,并对数据进行回显. 二.截图 登录界面: 文件浏览器,查看文件的保存路径:/data/data/com.amos.datasave/fi ...

  9. python学习笔记:第6天 小数据池和编码转换

    目录 1. id 和 == 2. 小数据池 3. 编码和解码 1. id 和 == id:id是一个内置的函数,可以查看变量存放的内存地址(实际上不是真正的物理地址,这里暂时这样理解),用于判断是变量 ...

随机推荐

  1. NODE编程(一)--Node功能的组织和重用

    Node开发面对的两个问题: 1.如何组织代码 2.如何进行异步编程. 一.Node功能的组织和重用 Node模块允许你从被引入文件中选择要暴露给程序的函数和变量.如果模块返回的函数或变量不止一个,那 ...

  2. SQL Server2008创建约束图解 转

    转自 http://www.cnblogs.com/longhs/p/3670307.html SQLServer 中有五种约束, Primary Key 约束. Foreign Key 约束. Un ...

  3. zlib导致Ubuntu登录管理器失效

    ubuntu版本:10.04 现象:开机之后无法启动登录管理器. 原因:zlib与登录管理器冲突. 解决:卸载zlib.

  4. u-boot移植为tiny6410步骤

    1. 修改顶层Makefile文件 2. 修改arch/arm/cpu/arm1176/s3c64xx/cpu_init.S 3. 修改arch/arm/cpu/arm1176/s3c64xx/Mak ...

  5. [改善Java代码]预防线程死锁

    线程死锁DeadLock是多线程编码中最头疼的问题,也是最难重现的问题,因为Java是单进程多线程语言.

  6. Linux 命令 - service: 系统服务管理

    命令格式 service SCRIPT COMMAND [OPTIONS] service --status-all service --help | -h | --version 实例 a) 查看 ...

  7. 一个js排序

     ]                           d = d[a];          e = e[a];                                d =         ...

  8. HDOJ2013蟠桃记

    蟠桃记 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Submiss ...

  9. Android 线程Thread的2种实现方法

    在讲解之前有以下三点要说明: 1.在Android中有两种实现线程Thread的方法: ①扩展java.long.Thread类: ②实现Runnable()接口: 2.Thread类是线程类,它有两 ...

  10. Android之图片应用

    package com.example.imagescale; import android.os.Bundle; import android.app.Activity; import androi ...