import io # io模块里面主要使用StringIo和BytesIo # StringIo f = io.StringIO() # 像使用open函数创建文件一样,生成一个句柄 # 可以直接向f里面写入数据 f.write("when i was young ,i'd listen to the radio\n") f.write("我是你爸爸\n") f.write("hello,mother fucker") # 获取内容可以通过getvalue函数 data = f.getvalue() print(data) print(type(data)) # 运行结果 ''' when i was young ,i'd listen to the radio 我是你爸爸 hello,mother fucker <class 'str'> ''' # 也可以在创建句柄的时候,直接写入数据 f1 = io.StringIO("六月的古明地盆") data = f1.read() # 但此时要用f.read()函数 print(data) print(type(data)) # 运行结果 ''' 六月的古明地盆 <class 'str'> ''' # StringIo,由名字也可以看出,只能写入字符串,如果要写入字节类型,需要使用BytesIo # BytesIo的用法和StringIo的用法基本一样,只是写入内容的形式不一样,前者为字节,后者为字符串 f = io.BytesIO() f.write(bytes("我是你爸 ", encoding="utf-8")) f.write(bytes("the feelings i have towards you is not lust,but limerence", encoding="utf-8")) data = f.getvalue() print(data) print(type(data)) # 运行结果 ''' b'\xe6\x88\x91\xe6\x98\xaf\xe4\xbd\xa0\xe7\x88\xb8 the feelings i have towards you is not lust,but limerence' <class 'bytes'> ''' # 使用BytesIo的时候,可以和StringIo一样在创建句柄的时候,写入数据 f = io.BytesIO(bytes("轩墨是我身下受", encoding="utf-8")) data = f.read() print(data) print(type(data)) # 运行结果 ''' b'\xe8\xbd\xa9\xe5\xa2\xa8\xe6\x98\xaf\xe6\x88\x91\xe8\xba\xab\xe4\xb8\x8b\xe5\x8f\x97' <class 'bytes'> '''
python--io
猜你喜欢
转载自www.cnblogs.com/traditional/p/9198270.html
今日推荐
周排行