在内存中打开文件

12

我正在开发一个Python 3.4项目。

有一种方法可以在内存中打开(sqlite3)数据库:

    with sqlite3.connect(":memory:") as database:

open()函数是否存在这样的技巧?例如:

   with open(":file_in_memory:") as myfile:

这个想法是为了加速一些测试函数对磁盘上的一些短文件进行打开/读取/写入操作;有没有办法确保这些操作在内存中进行?

3个回答

14

那么对于 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()

Python3: io.StringIO


10

io.StringIO中,对于类似于文件的输入/输出到字符串的情况也有类似的解决方案。

没有一种干净的方法可以将基于url的处理添加到普通的文件打开过程中,但由于Python是动态的,您可以monkey-patch标准的文件打开过程以处理这种情况。

例如:

from io import StringIO

old_open = open
in_memory_files = {}

def open(name, mode="r", *args, **kwargs):
     if name[:1] == ":" and name[-1:] == ":":
          # in-memory file
          if "w" in mode:
               in_memory_files[name] = ""
          f = StringIO(in_memory_files[name])
          oldclose = f.close
          def newclose():
              in_memory_files[name] = f.getvalue()
              oldclose()
          f.close = newclose
          return f
     else:
          return old_open(name, mode, *args, **kwargs)

之后你可以编写

f = open(":test:", "w")
f.write("This is a test\n")
f.close()

f = open(":test:")
print(f.read())

请注意,此示例非常简单,不能处理所有真实文件模式(例如追加模式,或在读取不存在的内存文件时引发正确的异常),但对于简单情况可能有效。

另请注意,所有内存文件将永远保留在内存中(除非您还修补 unlink)。

PS:我并不是说,猴子补丁标准的 openStringIO 实例是一个好主意,只是你可以这样做 :-D

PS2:这种问题在操作系统级别上更好地解决,方法是创建一个内存盘。通过这样做,您甚至可以调用外部程序,并从这些文件重定向它们的输出或输入,您还可以获得所有完整的支持,包括并发访问、目录列表等等。


3

io.StringIO 提供了一个内存文件实现,您可以使用它来模拟真实的文件。以下是文档中的示例:

import io

output = io.StringIO()
output.write('First line.\n')
print('Second line.', file=output)

# 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()

在Python 2中,这个类可以用StringIO.StringIO代替。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接