python - 打开内存中的文件

标签 python file python-3.x

(我正在处理一个 Python 3.4 项目。)

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

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

open() 函数是否存在这样的技巧?像这样的东西:

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

这个想法是为了加快一些测试功能打开/读取/写入磁盘上的一些短文件;有没有办法确保这些操作发生在内存中?

最佳答案

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

关于python - 打开内存中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23028071/

相关文章:

python 仅运行 apschedule BlockingScheduler 一次

python - 控制 Altair 区域的堆栈顺序

Java ASCII 输出到文件

c - fgets 在用户输入中引入新行

python - 计算 32 位整数列表中的非零位

python json转储可写性 "not write able"

python - 分解字符串列并计算字符频率

python - 如何更改管理端口?

python - 字典包含文本文件中的单词作为键,所有后续单词的列表作为值

python - 查找列表中出现次数最多的数字