#数据的读取除了通过文件,还可以在内存中进行。Python中的io模块提供了对str操作的StringIO函数。
#要把str写入StringIO,我们需要创建一个StringIO,然后像文件一样写入。操作示例如下:
1 #!/usr/bin/python3
2 #-*-coding:UTF-8-*-
3 #StringIO
4 
5 from io import StringIO
6 io_val=StringIO()
7 io_val.write('hello')
8 print('say:',io_val.getvalue())
#执行结果如下:
1 D:\Pythonworkspace>python StringIO.py
2 say: hello
#由执行结果看到,getvalue()用于获得写入后的str。要读取StringIO,还可以用str初始化StringIO,然后像读文件一样读取。操作示例如下:
 1 #!/usr/bin/python3
 2 #-*-coding:UTF-8-*-
 3 #StringIO
 4 
 5 from io import StringIO
 6 
 7 io_val=StringIO('Hello\nPython!\nWecome!')
 8 while True:
 9     line=io_val.readline()
10     if line=='':
11         break
12     print('line value:',line.strip())
#执行结果如下:
1 D:\Pythonworkspace>python StringIO.py
2 line value: Hello
3 line value: Python!
4 line value: Wecome!

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-12
  • 2021-11-19
  • 2021-06-07
  • 2021-10-25
猜你喜欢
  • 2021-09-23
  • 2021-06-15
  • 2021-07-19
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案