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
    评论
Python中,`io.BufferedRWPair`是一个将两个`io.RawIOBase`对象连接在一起的类,它提供了一个缓冲区,可以在两个对象之间进行读写操作。 `io.BufferedRWPair`类的构造函数如下所示: ```python io.BufferedRWPair(raw, raw2, buffer_size=DEFAULT_BUFFER_SIZE) ``` 其中,`raw`和`raw2`参数是两个`io.RawIOBase`对象,`buffer_size`参数是缓冲区大小,如果未提供则使用默认值`io.DEFAULT_BUFFER_SIZE`。 下面是一个示例,演示如何使用`io.BufferedRWPair`类将一个串口读写器与一个文件读写器连接在一起: ```python import serial import io # 打开串口 ser = serial.Serial('COM1', 9600, timeout=1) # 打开文件 with open('example.txt', mode='w') as f: # 创建串口读写器 ser_io = io.TextIOWrapper(io.BufferedRWPair(ser, ser), encoding='utf-8', newline='\r') # 创建文件读写器 file_io = io.TextIOWrapper(io.BufferedRWPair(f, f), encoding='utf-8') # 从串口读取文本数据,并写入文件 data = ser_io.readline() file_io.write(data) # 关闭串口 ser.close() ``` 在上面的示例中,我们首先使用`serial.Serial`函数打开串口,并设置串口参数。然后,我们使用`io.BufferedRWPair`函数创建一个串口读写器,并将其传递给`io.TextIOWrapper`函数以设置编码方式为`utf-8`,并设置换行符为`\r`。接下来,我们使用`open`函数打开文件,并使用`io.BufferedRWPair`函数创建一个文件读写器,并将其传递给`io.TextIOWrapper`函数以设置编码方式为`utf-8`。然后,我们使用`ser_io.readline()`函数从串口读取一行文本数据,并使用`file_io.write()`函数将其写入文件。最后,我们使用`ser.close()`函数关闭串口。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值