python-9-IO编程
1-文件读写
f = open('d:/file.txt','r') #如果文件不存在会报异常
print(f.read()) #一次性读取所有内容
f.close()
1.2 由于文件操作会用异常, 每次用try不方便
with open("d:/file.txt","r") as f:
print(f.read())
1.3 文件太大,一次性读取不科学,如果是配制文件
with open("d:/file.txt","r") as f:
for line in f.readlines():
print(line.strip())
1.4 指定字符编码
f = open('d:/file.txt', 'r', encoding='gbk',errors='ignore') #errors='ignore' 参数会忽略中的一些编码错误
f.read()
1.5 写文件,w会删除原来的,a是追加
f = open('d:/file.txt', 'a')
f.write("go out")
f.close()
https://docs.python.org/3/library/functions.html#open
2-StringIO和BytesIO
StringIO顾名思义就是在内存中读写str。
from io import StringIO
f = StringIO()
f.write('hello')
f.write(' ')
f.write('word!')
print(f.getvalue()) #hello word!
2.2 BytesIO
StringIO操作的只能是str,如果要操作二进制数据,就需要使用BytesIO
from io import BytesIO
f = BytesIO()
f.write('中文'.encode('utf-8'))
print(f.getvalue()) #b'\xe4\xb8\xad\xe6\x96\x87' #初始化BytesIO
from io import BytesIO
f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
print(f.read())
3-操作文件和目录
3.1环境变量
import os
os.environ#环境变量
os.environ.get('OS') #得到指定的key
3.2 文件路径操作
os.path.abspath(".")
os.path.join('d:/','fffff')
os.mkdir("d:/testdir") #如果存在创建会报错
os.rmdir("d:/testdir")
3.3 文件路径
os.path.split('/Users/michael/testdir/file.txt')#('/Users/michael/testdir', 'file.txt')
os.rename('test.txt', 'test.py') #对文件重命名
os.remove('test.py') #删除文件
[x for x in os.listdir('.') if os.path.isdir(x)] #列出当前目录下的所有目录
[x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1]=='.py'] #列出所有的.py文件
4-序列化操作(在其他语言中也被称之为serialization,marshalling,flattening等等)
import pickle
d = dict(name='Bob', age=20, score=88)
print(pickle.dumps(d)) f=open('dump.txt','wb')
pickle.dump(d,f) #序列化到文件
f.close()
4.2 反序列化
f = open('dump.txt','rb')
d=pickle.load(f)#反序列化
f.close()
print(d)
4.3 json序列化
import json
d = dict(name='Bob111', age=20, score=88)
print(json.dumps(d))
4.4 json序列化 进阶
import json
class Student(object):
def __init__(self,name,age,score):
self.name = name
self.age = age
self.score = score
s = Student('dashen', 20, 80) def student2dict(std):
return {
'name':std.name,
'age':std.age,
'score':std.score
}
print(json.dumps(s,default=student2dict))
print(json.dumps(s,default=lambda obj:obj.__dict__))
4.5 json反序列化
def dict2student(d):
return Student(d['name'], d['age'], d['score'])
json_str = '{"age": 20, "score": 88, "name": "Bob"}'
stu = json.loads(json_str, object_hook=dict2student)
print(stu.score) #88
python-9-IO编程的更多相关文章
- python异步IO编程(一)
python异步IO编程(一) 基础概念 协程:python generator与coroutine 异步IO (async IO):一种由多种语言实现的与语言无关的范例(或模型). asyncio ...
- python异步IO编程(二)
python异步IO编程(二) 目录 开门见山 Async IO设计模式 事件循环 asyncio 中的其他顶层函数 开门见山 下面我们用两个简单的例子来让你对异步IO有所了解 import asyn ...
- Python之IO编程——文件读写、StringIO/BytesIO、操作文件和目录、序列化
IO编程 IO在计算机中指Input/Output,也就是输入和输出.由于程序和运行时数据是在内存中驻留,由CPU这个超快的计算核心来执行,涉及到数据交换的地方,通常是磁盘.网络等,就需要IO接口.从 ...
- Python之IO编程
前言:由于程序和运行数据是在内存中驻留的,由CPU这个超快的计算核心来执行.当涉及到数据交换的地方,通常是磁盘.网络等,就需要IO接口.由于CPU和内存的速度远远高于外设的速度,那么在IO编程中就存在 ...
- python同步IO编程——基本概念和文件的读写
IO——Input/Output,即输入输出.对于计算机来说,程序运行时候数据是在内存中的,涉及到数据交换的地方,通常是磁盘.网络等.比如通过浏览器访问一个网站,浏览器首先把请求数据发送给网站服务器, ...
- Python笔记-IO编程
IO在计算机中是指input和output(数据输入与输出),涉及到数据交换(磁盘.网络)的地方就需要IO接口. 输入流input stream是指数据从外面(磁盘.网络服务器)流入内存:输出流out ...
- 【Python】IO编程
文件读写 StringIO和BytesIO 操作文件和目录 序列化 学习廖老师的py官网的笔记 1.stream的概念.数据交换通常需要建立两根“水管”. 2.同步IO和异步IO.异步性能高,但是编程 ...
- 【Python】[IO编程]文件读写,StringIO和BytesIO,操作文件和目录,序列化
IO在计算机中指Input/Output,也就是输入和输出. 1.文件读写,1,读文件[使用Python内置函数,open,传入文件名标示符] >>> f = open('/User ...
- python同步IO编程——StringIO、BytesIO和stream position
主要介绍python两个内存读写IO:StringIO和BytesIO,使得读写文件具有一致的接口 StringIO 内存中读写str.需要导入StringIO >>> from i ...
- Python中IO编程-StringIO和BytesIO
Python在内存中读写数据,用到的模块是StringIO和BytesIO StringIO >>> from io import StringIO >>> f = ...
随机推荐
- svg的基本图形与属性【小尾巴的svg学习笔记1】
因为项目有可能用到, 所以学习了一下,做此笔记,图截自慕课网,侵删. 一.基本图形 1.矩形 x,y定义矩形的左上角坐标: width,height定义矩形的长度和宽度: rx,ry定义矩形的圆角半径 ...
- canvas的isPoinInPath API实现交互
- canvas绘制圆环
- 使用ionic cordova build android --release --prod命令打包报错解决方法
使用ionic cordova build android --release --prod命令打包报有如下错误及解决方法 只要把以下内容添加到build-extras.gradle或(build** ...
- unity工具介绍
MemoryProfiler内存分析工具 行为树 behaviac github 场景动画编辑器 Snapdragon Profiler性能分析工具 VTune性能分析器 protobuf数据交换格式 ...
- gradle方式集成融云sdk dlopen failed: library "libsqlite.so" not found
1.gradle implementation 'cn.rongcloud.android:IMLib:2.8.6' implementation 'cn.rongcloud.android:IMKi ...
- Struts2_带参数的结果集
页面请求: <a href="user/user?type=1">传参数</a> action: public Integer type; public S ...
- SonarQube代码质量管理平台介绍与搭建
前 言 1.SonarQube的介绍 SonarQube是一个管理代码质量的开放平台. 可以从七个维度检测代码质量(为什么要用SonarQube): (1) 复杂度分布(complexity):代码复 ...
- python数组列表、字典、拷贝、字符串
python中字符串方法 name = "I teased at life as if it were a foolish game" print(name.capitalize( ...
- Ubuntu ndk环境变量配置
https://blog.csdn.net/gulingfengze/article/details/70149092 用source /etc/profile,有些博客写的使用sudo gedit ...