博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python-9-IO编程
阅读量:4335 次
发布时间:2019-06-07

本文共 2391 字,大约阅读时间需要 7 分钟。

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()

2-StringIO和BytesIO

  StringIO顾名思义就是在内存中读写str。

from io import StringIOf = StringIO()f.write('hello')f.write(' ')f.write('word!')print(f.getvalue()) #hello word!

 2.2 BytesIO

    StringIO操作的只能是str,如果要操作二进制数据,就需要使用BytesIO

from io import BytesIOf = BytesIO()f.write('中文'.encode('utf-8'))print(f.getvalue()) #b'\xe4\xb8\xad\xe6\x96\x87'#初始化BytesIOfrom io import BytesIOf = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')print(f.read())

3-操作文件和目录

 3.1环境变量

import osos.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 pickled = 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 jsond = dict(name='Bob111', age=20, score=88)print(json.dumps(d))

4.4 json序列化 进阶

import jsonclass Student(object):    def __init__(self,name,age,score):        self.name = name        self.age = age        self.score = scores = 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

 

转载于:https://www.cnblogs.com/qinzb/p/9041347.html

你可能感兴趣的文章
[PYTHON]一个简单的单元測试框架
查看>>
iOS开发网络篇—XML数据的解析
查看>>
[BZOJ4303]数列
查看>>
一般处理程序在VS2012中打开问题
查看>>
C语言中的++和--
查看>>
thinkphp3.2.3入口文件详解
查看>>
POJ 1141 Brackets Sequence
查看>>
Ubuntu 18.04 root 使用ssh密钥远程登陆
查看>>
Servlet和JSP的异同。
查看>>
虚拟机centOs Linux与Windows之间的文件传输
查看>>
ethereum(以太坊)(二)--合约中属性和行为的访问权限
查看>>
IOS内存管理
查看>>
middle
查看>>
[Bzoj1009][HNOI2008]GT考试(动态规划)
查看>>
Blob(二进制)、byte[]、long、date之间的类型转换
查看>>
OO第一次总结博客
查看>>
day7
查看>>
iphone移动端踩坑
查看>>
vs无法加载项目
查看>>
Beanutils基本用法
查看>>