python学习三(数据保存到文件)
2013-11-23 17:57
609 查看
以写模式打开文件:需要指定写模式,如下所示
如果文件已经存在,则会清空它现有的所有内容。要追加一个文件,需要使用访问模式a,会追加到下一行。
例子:将上节中Man和Other Man说的话,分别保存到两个文件中
使用with open()方法保存文件,不需要再用close方法关闭文件
Python提供了一个标准库,名为pickle,它可以加载、保存几乎任何的Python数据对象,包括列表
使用python的dump保存,load恢复
'wb'中的b表示以二进制模式打开文件
要读取二进制文件使用'rb'
data = open('data.out','w')
如果文件已经存在,则会清空它现有的所有内容。要追加一个文件,需要使用访问模式a,会追加到下一行。
例子:将上节中Man和Other Man说的话,分别保存到两个文件中
man = [] other = [] try: data = open('sketch.txt') for each_line in data: try: (role, line_spoken) = each_line.split(':') line_spoken = line_spoken.strip() if role == 'Man': man.append(line_spoken) elif role == 'Other Man': other.append(line_spoken) else: pass except ValueError: pass data.close() except IOError: print('The datafile is missing!') #使用print将列表中的数据输出到文件中 try: with open('man_data.txt', 'w') as man_file, open('other_data.txt', 'w') as other_file: print(man, file=man_file) print(other, file=other_file) except IOError as err: print('File error: ' + str(err))
使用with open()方法保存文件,不需要再用close方法关闭文件
Python提供了一个标准库,名为pickle,它可以加载、保存几乎任何的Python数据对象,包括列表
使用python的dump保存,load恢复
import pickle man = [] other = [] try: data = open('sketch.txt') for each_line in data: try: (role, line_spoken) = each_line.split(':') line_spoken = line_spoken.strip() if role == 'Man': man.append(line_spoken) elif role == 'Other Man': other.append(line_spoken) else: pass except ValueError: pass data.close() except IOError: print('The datafile is missing!') try: with open('man_data.txt', 'wb') as man_file, open('other_data.txt', 'wb') as other_file: pickle.dump(man, file=man_file) pickle.dump(other, file=other_file) except IOError as err: print('File error: ' + str(err)) except pickle.PickleError as perr: print('Pickling error: ' + str(perr))
'wb'中的b表示以二进制模式打开文件
要读取二进制文件使用'rb'
import pickle with open('man_data.txt','rb') as readText: a_list = pickle.load(readText) print(a_list)
相关文章推荐
- Python Scrapy学习之pipelines不能保存数据到文件问题
- Python学习笔记_Chapter 4数据保存到文件
- 个人学习代码保存:例11.读取Excel文件中的数据
- Python备份文件、文件版本的学生管理系统如何实现(将数据保存在txt文件中)
- python通过串口读取GPS NMEA格式的数据,并保存为csv文件
- 【原】Learning Spark (Python版) 学习笔记(二)----键值对、数据读取与保存、共享特性
- Python爬虫(入门+进阶)学习笔记 1-5 使用pandas保存豆瓣短评数据
- Python学习_我该怎么读取文件中的数据并操作文件
- 个人学习代码保存:例12.读取GridView文件中的数据到Excel文件
- python学习之----用虚拟环境保存库文件
- Python MySQL读出数据后保存到文件时中文乱码解决
- python使用h5py读取mat文件数据,并保存图像
- python保存数据到本地文件的方法
- Python学习笔记之爬取网页保存到本地文件
- python爬虫由浅入深9---定向爬取股票数据信息并保存至本地文件
- Python 学习(4)---文件的读写操作以及数据的腌制
- Python 通过print_lol将数据保存到文件中
- 几行Python代码生成饭店营业额模拟数据并保存为CSV文件
- Python爬虫学习--WIN10下定时获取CSDN个人的访问量并保存到文件中2018/01/19
- Python数据处理-将数据保存为txt、csv等文件格式方法