Skip to content

Commit 278f28f

Browse files
committed
StringIO
StringIO
1 parent aa16a86 commit 278f28f

2 files changed

Lines changed: 51 additions & 0 deletions

File tree

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# Python在内存中读写数据
2+
有时候数据不一定要读写到文件中,可以再内存中进行读写操作。
3+
4+
有些场景本地不保存数据,从远程读取文件数据到本地内存中进行处理后,再把数据流推送到远程,从头到尾本地并不生成文件。
5+
6+
**比如读取服务器一个加密文件数据流到内存中,在内存中进行解析处理,最终将解密后的数据流推送到服务器,中间不需要在本地保存加密文件,直接在内存中处理,减少了IO操作。**
7+
## StringIO
8+
```python
9+
from io import StringIO
10+
11+
if __name__ == '__main__':
12+
s = StringIO()
13+
s.write('123\n')
14+
s.write('456\n')
15+
s.write('aaa\n')
16+
s.write('bbb')
17+
print(s) # <_io.StringIO object at 0x0000022F7440F9D8>
18+
# 获取写入的内容
19+
print(s.getvalue()) # '123\n456\naaa\nbbb'
20+
# tell()方法返回文件指针当前位置
21+
print(s.tell()) # 15
22+
23+
# seek(offset, whence)方法用于移动文件读取指针到指定位置
24+
# offset:代表需要移动偏移的字节数
25+
# whence:默认0,表示要从哪个位置开始偏移;0代表从文件开头开始算起,1代表从当前位置开始算起,2代表从文件末尾算起。
26+
s.seek(0, 0)
27+
28+
print(s.tell()) # 0
29+
print(s.readlines()) # ['123\n', '456\n', 'aaa\n', 'bbb']
30+
31+
print(s.tell()) # 15
32+
print(s.readlines()) # []
33+
```
34+
35+
## BytesIO
36+
```python
37+
from io import BytesIO
38+
39+
if __name__ == '__main__':
40+
f = BytesIO()
41+
42+
fr = open('test.mp4', 'rb')
43+
f.write(fr.read())
44+
fr.close()
45+
46+
# 对视频流解析处理
47+
48+
with open('local_test.mp4', 'wb') as fw:
49+
fw.write(f.getvalue())
50+
```

python_basic/main.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,4 @@
2727
* [@property 保护变量的访问与设置](保护变量的访问与设置.md)
2828
* [Python函数参数的传递机制](Python函数参数的传递机制.md)
2929
* [Python猴子补丁 monkey patch](猴子补丁.md)
30+
* [Python在内存中读写数据StringIO/BytesIO](Python在内存中读写数据.md)

0 commit comments

Comments
 (0)