python程序设计——文件操作
2024-10-21 14:28:34
分类
1.文本文件
存储常规字符串,由若干文本行组成,每行以换行符'\n'结尾
2.二进制文件
把对象以字节串存储,常见的图形图像、可执行文件、数据库文件office文档等
#创建文件
>>fw = open('sample.txt','w+',encoding='utf-8')
>>s = '文本读取方式\n sample.txt w+\n'
>>fw.write(s)
>>fw.close()
#查看sample.txt
文本读取方式
sample.txt w+ #建议形式,关键字with可以自动管理资源
>>s = '文本读取方式\n sample.txt w+\n'
>>with open('sample.txt','w+',encoding='utf-8') as fw:
>> fw.write(s)
# 判断文件对象是否关闭
>>fw.colsed
True #添加文件内容
>>s = 'hello\n'
>>with open('sample.txt','a+',encoding='utf-8') as fa:
>> fa.write(s)
文本读取方式
sample.txt w+
hello # 读取文件内容
# 读取一行
>>fread = open('sample.txt','r',encoding='utf-8')
>>fread.readline()
'文本读取方式\n'
>>fread.readline()
' sample.txt w+\n'
>>fread.readline()
'hello\n' # 一次读取所有行
>>fread = open('sample.txt','r',encoding='utf-8')
>>fread.readlines()
['文本读取方式\n', ' sample.txt w+\n', 'hello\n'] #读取固定字符个数
>>fread = open('sample.txt','r',encoding='utf-8')
>>fread.read(4)
'文本读取'
45 >>fread.close()
可以使用dir() 查看与对象相关的方法,使用help()查看方法的用法
>>fread = open('sample.txt','r',encoding='utf-8')
>>fread.colse()
>>dir(fread)
#查看read()函数用法
>>help(fread.read)
文件序列化
序列化,就是把内存中的数据在不丢失数据类型的情况下,转化为二进制形式的过程
1.使用pickle模块
Pickle是常用并且快速的二进制文件序列化模块
#使用pickle dump依次写入二进制文件
import pickle
f = open('sample_pickle.dat','wb') alist = [[2,3,4],[6,7,8]]
aset = {'a','b','c'}
atuple = (-5,-3,-1)
astr = '北京欢迎你,welcome!'
adic = {'name':'jin','sex':None}
try:
pickle.dump(alist,f)
pickle.dump(aset,f)
pickle.dump(atuple,f)
pickle.dump(astr,f)
pickle.dump(adic,f)
except:
print('write error')
finally:
f.close() #使用Pickle load依次读取二进制文件
fr = open('sample_pickle.dat','rb')
try:
x=pickle.load(fr)
print(x)
x=pickle.load(fr)
print(x)
x=pickle.load(fr)
print(x)
x=pickle.load(fr)
print(x)
x=pickle.load(fr)
print(x)
except:
print('read error')
finally:
fr.close()
2.使用struct模块
import struct
import binascii values = (1, b'good', 1.22) #字符串必须为字节流类型
s = struct.Struct('I4sf')
packed_data = s.pack(*values) #序列解包
unpacked_data = s.unpack(packed_data) print('Original values:', values)
print('Format string :', s.format)
print('Uses :', s.size, 'bytes')
print('Packed Value :', binascii.hexlify(packed_data))
print('Unpacked Type :', type(unpacked_data), ' Value:', unpacked_data) out:
Original values: (1, b'good', 1.22)
Format string : b'I4sf'
Uses : 12 bytes
Packed Value : b'01000000676f6f64f6289c3f'
Unpacked Type : <class 'tuple'> Value: (1, b'good', 1.2200000286102295)
最新文章
- 图解jmeter压测http接口
- 一次APP测试的感悟
- 学习ASP.NET MVC(七)——我的第一个ASP.NET MVC 查询页面
- 【xml】利用OpenCV解析
- Laravel错误与日志处理
- 使用Webpack和Babel来搭建React应用程序
- JavaScript的apply和call方法及其区别
- setLayoutParams getLayoutParams
- MySQL 5.6初始配置调整
- yii2源码学习笔记(五)
- PHP设计模式笔记四:适配器模式 -- Rango韩老师 http://www.imooc.com/learn/236
- C#关闭显示屏,使显示屏处于待机状态
- 为什么Java项目前会出现一个红色感叹号!
- 15分钟快速开发一个kissy组件(流程篇)
- 转载:org.apache.catalina.util.DefaultAnnotationProcessor cannot be cast to org.apache.Annotation
- 【Luogu1273】有线电视网(动态规划)
- pkg-config 详解
- python的学习和使用
- 详细解读大数据分析引擎Pig&;PigLatin语句
- day 82 URL分发