Python 在内存中打开一个文件

Python 在内存中打开一个文件,python,file,python-3.x,Python,File,Python 3.x,(我正在从事一个Python 3.4项目。) 有一种方法可以在内存中打开(sqlite3)数据库: with sqlite3.connect(":memory:") as database: open()函数是否存在这样的技巧?比如: with open(":file_in_memory:") as myfile: 其想法是加速一些测试函数在磁盘上打开/读取/写入一些短文件;有没有办法确保这些操作发生在内存中?如何: python3:提供了一个内存文件实现,可用于模拟真实文件。

(我正在从事一个Python 3.4项目。)

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

    with sqlite3.connect(":memory:") as database:
open()函数是否存在这样的技巧?比如:

   with open(":file_in_memory:") as myfile:
其想法是加速一些测试函数在磁盘上打开/读取/写入一些短文件;有没有办法确保这些操作发生在内存中?

如何:

python3:

提供了一个内存文件实现,可用于模拟真实文件。文档中的示例:

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

在Python2中,此类可用作。

中的字符串的类似文件输入/输出

没有一种干净的方法可以将基于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())
请注意,此示例非常简单,不处理所有实际文件模式(例如,追加模式,或在以读取模式打开内存中不存在的文件时引发适当的异常),但它可能适用于简单情况

还请注意,所有内存中的文件将永远保留在内存中(除非您同时修补
取消链接

PS:我并不是说monkey patching standard open或
StringIO
实例是个好主意,只是你可以:-D

PS2:通过在ram中创建磁盘,在操作系统级别更好地解决了这类问题。有了它,您甚至可以调用外部程序重定向这些文件的输出或输入,您还可以获得所有的全面支持,包括并发访问、目录列表等

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

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