如何进行虚拟文件处理? [英] How to do virtual file processing?

查看:54
本文介绍了如何进行虚拟文件处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,为了创建文件,我使用以下内容:

So for creating files I use the following:

fileHandle = open('fileName', 'w')

然后将内容写入文件,关闭文件. 在下一步中,我处理文件. 在该程序的最后,我得到一个需要删除的物理文件".

then write the contents to the file, close the file. In the next step I process the file. At the end of the program, I end up with a "physical file" that I need to delete.

是否有一种方法可以编写行为与物理"文件完全相同的虚拟"文件(允许以相同的方式对其进行操作),但在Python运行结束时不存在该文件?

Is there a way to write a "virtual" file that behaves exactly like a "physical" one (allowing it to be manipulated the same way) but does not exist at the end of the run in Python?

推荐答案

您可能要考虑使用

You might want to consider using a tempfile.SpooledTemporaryFile which gives you the best of both worlds in the sense that it will create a temporary memory-based virtual file initially but will automatically switch to a physical disk-based file if the data held in memory exceeds a specified size.

另一个不错的功能是(使用内存时)它将自动使用 io.StringIO 取决于所使用的mode-允许您对其读写Unicode字符串或二进制数据(字节).

Another nice feature is that (when using memory) it will automatically use either an io.BytesIO or io.StringIO depending on what mode is being used—allowing you to either read and write Unicode strings or binary data (bytes) to it.

唯一棘手的部分可能是您需要避免在步骤之间关闭文件,因为这样做可能会导致文件从内存或磁盘中删除.相反,您可以使用文件 方法调用.

The only tricky part might be the fact that you'll need to avoid closing the file between steps because doing so would cause it to be deleted from memory or disk. Instead you can just rewind it back to the beginning with a file seek(0) method call.

当文件完全处理完并关闭后,如果其中的数据量过多,则会自动将其从磁盘上删除.

When you are completely done with the file and close it, it will automatically be deleted from disk if the amount of data in it caused it to be rolled-over to a physical file.

这篇关于如何进行虚拟文件处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆