io BytesIO StringIO

Python I/O: (Input Output)
StringIO:
很多时候,数据读写不一定是文件,也可以在内存中读写。
StringIO顾名思义就是在内存中读写str。
要把str写入StringIO,我们需要先创建一个StringIO,然后,像文件一样写入即可:

# -*- coding: utf-8 -*-
from io import StringIO
f = StringIO()
f.write('hello')
f.write(' ')
f.write('world!')
print(f.getvalue())  #hello world!

BytesIO
StringIO操作的只能是str,如果要操作二进制数据,就需要使用BytesIO。
BytesIO实现了在内存中读写bytes,我们创建一个BytesIO,然后写入一些bytes:

from io import BytesIO
f = BytesIO()
f.write('中文'.encode('utf-8'))

print(f.getvalue())  #b'\xe4\xb8\xad\xe6\x96\x87'

请注意,写入的不是str,而是经过UTF-8编码的bytes。
和StringIO类似,可以用一个bytes初始化BytesIO,然后,像读文件一样读取:

from io import BytesIO
f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
print(f.read())   #b'\xe4\xb8\xad\xe6\x96\x87'
from pyftpdlib.authorizers import DummyAuthorizer from pyftpdlib.handlers import FTPHandler,ThrottledDTPHandler from pyftpdlib.servers import FTPServer from pyftpdlib.log import LogFormatter import logging import configparser import pyftpdlib logger = logging.getLogger() logger.setLevel(logging.INFO) ch = logging.StreamHandler() fh = logging.FileHandler(filename='myftpserver.log',encoding='GBK') ch.setFormatter(LogFormatter()) fh.setFormatter(LogFormatter()) logger.addHandler(ch) logger.addHandler(fh) authorizer = DummyAuthorizer() authorizer.add_user("user", "12345", "d:/", perm="elradfmw") ENABLE_ANONYMOUS = 'on' if ENABLE_ANONYMOUS == 'on': authorizer.add_anonymous("d:/") handler = FTPHandler handler.authorizer = authorizer handler.passive_ports = range(8300, 8500) dtp_handler = ThrottledDTPHandler upload = 100 * 1024 #100kb/s download = 100 * 1024 #100kb/s dtp_handler = ThrottledDTPHandler dtp_handler.read_limit = download dtp_handler.write_limit = upload ip = '0.0.0.0' port = '21' server = FTPServer((ip, port), handler) Max_con = 100 server.max_per_ip = 10 server.max_cons = Max_con server.max_cons_per_ip =server.max_per_ip server.serve_forever() #创建文件 import ftplib from io import StringIO import io from ftplib import FTP ftp = FTP(host='localhost',user='user',passwd='12345') ftp.cwd('test') ftp.storlines('STOR poem.txt',io.StringIO('') ) ftp.quit() #写入数据 from io import StringIO import io from ftplib import FTP ftp = FTP(host='localhost',user='user',passwd='12345') ftp.cwd('test') binary_data = b'Hello, world!' text = binary_data.decode('utf-8') data_as_bytes = text.encode('utf-8') ftp.storlines('STOR test.txt',io.BytesIO(data_as_bytes)) #上传下载文件 from ftplib import FTP ftp = FTP(host='localhost',user='user',passwd='12345') ftp.encoding = 'gbk' ftp.cwd('test') ftp.retrlines('LIST') ftp.retrbinary('RETR poem.txt', open('poem.txt', 'wb').write) ftp.storbinary('STOR ftpserver.py', open('ftpserver.py', 'rb')) for f in ftp.mlsd(path='/test'): print(f)这段代码的数据处理分析
05-18
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值