[Head First Python]4.读取文件datafile.txt, 去除两边空格, 存储到列表,从列表格式化(nester.py)后输出到文件man.out,other.out
2014-06-17 16:54
841 查看
datafile.txt #文件
nester.py #输出模块 第2章文件nester.py修改后的模块,安装到你的python环境中
sketch.py #读取文件datafile.txt, 去除两边空格, 存储到列表,从列表格式化(nester.py)后输出到文件man.out,other.out
man.out
other.out
Man: this is the right room for an argument. Other Man: I've told you once. Man: No you haven't Other Man: Yes, I have. (pause) 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!
nester.py #输出模块 第2章文件nester.py修改后的模块,安装到你的python环境中
def print_lol(the_list, indent = False, level = 0, fn = sys.stdout): for each_item in the_list: if isinstance(each_item,list): print_lol(each_item, indent, level + 1, fn); else: if indent: for tab_stop in range(level): print("\t",end='', file = fn) print(each_item, file = fn)
sketch.py #读取文件datafile.txt, 去除两边空格, 存储到列表,从列表格式化(nester.py)后输出到文件man.out,other.out
import nester man = [] other = [] try: data = open ("datafile.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('this data file is missing!') try: with open('man.out', 'w') as man_out, open('other.out','w') as other_out: nester.print_lol(man, fn = man_out) nester.print_lol(other, fn = other_out) except fileError as err: print('file error' + str(err))
man.out
this is the right room for an argument. No you haven't When? No you didn't You didn't
other.out
I've told you once. Yes, I have. Just now. Yes I did. I'm telling you, I did!
相关文章推荐
- 从一个名为 in_file.txt 的文本文件中读取单词,然后把每个词写到一个名为out_file.txt的输出文件中 并且每个词之间用空格分开
- 读取关键字配置文件,并将关键字放入到一个列表中(去重复去和空格)--PYTHON
- Head First Python 学习笔记-Chapter3:文件读取和异常处理
- Head First Python 学习笔记-Chapter3:文件读取和异常处理
- Python2.x 脚本批量串行select查询数据库,格式化输出到txt文件
- Python读取txt文件后去除每行后面的\n
- python读取txt文件中的字符串,并将其中的数字输出
- HeadFirstPython---------(二)第四章,持久存储,数据保存到文件
- Head First Python 第二章 函数模块&第三章 文件与异常&第四章 持久存储&第五章 处理数据
- txt文件中存储多行标题+空格+作者名,现按格式“标题+|+作者”的形式输出
- [文件] Python读取txt存储至xls
- Head First Python---------(一)第一章(初识Python__人人都爱列表)、第二章(共享你的代码__函数模块)、第三章(文件与异常__处理错误)
- linux c去除空格 和读取配置文件中的键值对中的值
- python读取文件同时输出行号和内容
- Head First Java(4)—— 序列化和文件的输入/输出
- 从键盘多行输入,写入TXT文件并读取输出~只显示第一行,如何解决?(答案见代码)
- python 学习记录(11)-文件处理/读取文件/文件写入内容/文件删除/文件复制/文件重命名/后缀名/内容查找与替换/文件比较/ 配置文件访问/目录创建与删除/遍历目录/定向输出
- Java 读取文件大写和格式化输出字串
- java 输入输出 格式化 本地文件的读取
- Java 读取文件大写和格式化输出字串