【发布时间】:2017-11-06 22:52:58
【问题描述】:
为了不重写一个开源库,我想在python 3中将一串文本视为一个文件。
假设我将文件内容作为字符串:
not_a_file = 'there is a lot of blah blah in this so-called file'
我想将此变量(即文件的内容)视为path-like object,这样我就可以在python的open()function中使用它。
这是一个简单的例子,说明了我的困境:
not_a_file = 'there is a lot of blah blah in this so-called file'
file_ptr = open(not_a_file, 'r')
显然该示例不起作用,因为not_a_file 不是类似路径的对象。出于可移植性目的,我不想编写文件或创建任何临时目录。
话虽如此,我需要解开这个谜团:
not_a_file = 'there is a lot of blah blah in this so-called file'
... Something goes here ...
file_ptr = open(also_not_a_file, 'r')
到目前为止我已经尝试过什么
我已经研究过 StringIO 并尝试将其用作类似路径的对象并且没有骰子:
import StringIO output = StringIO.StringIO() output.write('First line.\n') file_ptr = open(output,'r')好吧,这不起作用,因为 StringIO 不是类似路径的对象。我以类似的方式尝试了 tempfile,但没有成功。
import tempfile tp = tempfile.TemporaryFile() tp.write(b'there is a lot of blah blah in this so-called file') open(tp,'r')- 最后我尝试了mmap,看看是否可以将字符串写入内存,然后用
open打开内存指针,没有成功。
感谢任何帮助! :-)
编辑 1:我想解决的问题
如果PurePath 被初始化为一个文件,那么pathlib.PurePath 可以与open() 一起工作。也许我可以创建一个继承 PurePath 的类的实例,当open() 读取时,它会读取我的字符串。举个例子吧:
from pathlib import PurePath
not_a_file = 'there is a lot of blah blah in this so-called file'
class Magic(PurePath):
def __init__(self, string_input):
self.file_content = string_input
PurePath.__init__(self, 'Something magical goes here')
#some more magic happens in this class
also_not_a_file = Magic(not_a_file)
fp = open(also_not_a_file,'r')
print(fp.readlines()) # 'there is a lot of blah blah in this so-called file'
【问题讨论】:
-
为什么要使用open命令? output.write("第 1 行\n"); output.seek(0); file_ptr=输出
-
@clockwatcher 所以在我要使用的另一个库中,有这个
open命令需要通常的文件输入。出于我的目的和可移植性,我需要以某种方式将字符串传递给open。 -
有没有办法使用带有字符串的 pathlib.PurePath 来创建一个可以读取字符串的对象?
open(pathlib.PurePath('path/to/filename.ext'),'r')是有效的 python。我可以将PurePath和我的字符串合并到一个类中,当传递给open()时读取我的字符串?