Ste*_*ton 57 python virtual file
因此,对于创建文件,我使用以下内容:
fileHandle = open('fileName', 'w')
Run Code Online (Sandbox Code Playgroud)
然后将内容写入文件,关闭文件.在下一步中,我处理文件.在程序结束时,我最终得到了一个我需要删除的"物理文件".
有没有写一个"虚拟"的文件,它的行为完全像一个"物理"一个(允许其操作方法相同),但在Python中运行结束时不存在的方式吗?
mar*_*eau 58
你可能想要考虑使用一个tempfile.SpooledTemporaryFile最好的两个世界,因为它最初将创建一个临时的基于内存的虚拟文件,但如果内存中保存的数据超过指定的数据,它将自动切换到基于物理磁盘的文件尺寸.
另一个不错的功能是(当使用内存时)它将自动使用io.BytesIO或io.StringIO依赖于mode正在使用的内容 - 允许您读取和写入Unicode字符串或二进制数据(字节).
唯一棘手的部分可能是您需要避免在步骤之间关闭文件,因为这样做会导致它从内存或磁盘中删除.相反,您可以通过文件seek(0)方法调用将其回退到开头.
当您完成文件并将其关闭后,如果文件中的数据量导致它被转移到物理文件,它将自动从磁盘中删除.
Vik*_*kez 48
你有StringIO和BytesIO在io模块中.
StringIO行为就像在文本模式下打开的文件-读写Unicode字符串(相当于打开一个文件io.open(filename, mode, encoding='...')),以及BytesIO像二进制模式(打开的文件的行为mode='[rw]b'),并能读写字节.
Python 2:
In [4]: f = io.BytesIO('test')
In [5]: type(f.read())
Out[5]: str
In [6]: f = io.StringIO(u'test')
In [7]: type(f.read())
Out[7]: unicode
Run Code Online (Sandbox Code Playgroud)
Python 3:
In [2]: f = io.BytesIO(b'test')
In [3]: type(f.read())
Out[3]: builtins.bytes
In [4]: f = io.StringIO('test')
In [5]: type(f.read())
Out[5]: builtins.str
Run Code Online (Sandbox Code Playgroud)
Sri*_*thy 12
您可以从官方文档中将StringIO用作虚拟文件
import StringIO
output = StringIO.StringIO()
output.write('First line.\n')
print >>output, 'Second line.'
# Retrieve file contents -- this will be
# 'First line.\nSecond line.\n'
contents = output.getvalue()
# Close object and discard memory buffer --
# .getvalue() will now raise an exception.
output.close()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
41149 次 |
| 最近记录: |