python 的IO

python 的IO

同步IO

文件IO

读文件

和C++大致一致

f = open('test.txt', 'r')
print(f.read())
f.close()

不过因为比C++的trycatch多了finally,所以之后应该这么做:

try:
    f = open('test.txt', 'r')
    print(f.read())
finally:
    if f:
        f.close()
更简单地写法

python 引入了 with

 with open('test.txt', 'r') as f:
    print(f.read())
更多地参数
  • 二进制: b

字符编码

  • 默认是utf8,如果不是utf8的话,就加上encoding='gbk'

写文件

写文件和读文件类似,只需要把read换成write即可。打开文件的时候 r 换成 w

with open('test.txt', 'w') as f:
    f.write('hello world')

StringIO

StringIO是一个内存中的字符串
读写方法和文件类似,只不过没有open()

from io import StringIO
f = StringIO()
f.write('hello world')
print(f.getvalue())

BytesIO

BytesIO是一个内存中的字节流
读写方法和文件类似,只不过没有open()

from io import BytesIO
f = BytesIO()
f.write('hello world'.encode())
print(f.getvalue().decode())
print(f.read()) 

OS中的文件和目录操作

环境变量

  • os.environ 是一个字典,里面存放了系统的环境变量
  • os.getenv(key) 获取某个环境变量的值
  • os.putenv(key, value) 设置某个环境变量的值, (普通用户不能用)
  • os.unsetenv(key) 删除某个环境变量(普通用户不能用)
print(os.environ)
print(os.getenv('PATH'))
os.putenv('TEST', 'hello world')
print(os.environ['TEST'])
del os.environ['TEST']

操作目录和文件

  • os.listdir(path) 列出某个目录下的所有文件名,返回一个列表
  • os.path.abspath(path) 获取绝对路径
  • os.path.join(*paths) 把多个路径合并成一个路径,返回一个字符串
  • os.mkdir(path) 创建一个目录
  • os.rmdir(path) 删除一个空的目录
    print(os.listdir('.'))
    print(os.path.abspath('.'))
    print(os.path.basename(__file__))
    print(os.path.dirname(__file__))
    print(os.path.join('.', 'test_file.txt'))
    print(os.path.exists('./test_file.txt'))
    print(os.path.isdir('./test_file.txt'))
    print(os.path.split( os.path.abspath(__file__)))
    if not os.path.exists('./test_dir'):
        os.makedirs('./test_dir')
    os.rmdir('./test_dir')

序列化

pickle

pickle是python自带的一个模块,用于序列化和反序列化。
pickle.dump(obj, file) 把对象写入文件中

import pickle
d = dict(name='Bob', age=20, score=88)
with open('test_file.txt', 'wb') as f:
    f.write(pickle.dumps(d))

json

    s = Student('Bob', 20, 88)
    print(student2dict(s))
    d = dict(name='Bob', age=20, score=88)
    print(json.dumps(d, default=student2dict))
    with open('test_file.json', 'w') as f:
        json.dump(student2dict(s), f)
    with open('test_file.json', 'r') as f:
        s = dict2student(json.load(f))
    print(s)
    print(student2dict(s))
  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值