为了不重写开源库,我想将一串文本视为python 3中的文件.
假设我将文件内容作为字符串:
not_a_file = 'there is a lot of blah blah in this so-called file'
Run Code Online (Sandbox Code Playgroud)
我想把这个变量,即文件的内容,作为一个 类似路径的对象,我可以在python的open() 函数中使用它.
这是一个显示我的困境的简单例子:
not_a_file = 'there is a lot of blah blah in this so-called file'
file_ptr = open(not_a_file, 'r')
Run Code Online (Sandbox Code Playgroud)
显然,该示例不起作用,因为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')
Run Code Online (Sandbox Code Playgroud)
我已经研究过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')
open,但没有成功.任何帮助表示赞赏!:-)
因此pathlib.PurePath,open()如果将PurePath初始化为文件,则可以使用.也许我可以创建一个继承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'
Run Code Online (Sandbox Code Playgroud)
StringIO返回一个StringIO对象,它几乎等同于该open语句返回的文件对象。因此,基本上,您可以使用StringIO代替该open语句。
# from io import StringIO for python 3
from StringIO import StringIO
with StringIO('there is a lot of blah blah in this so-called file') as f:
print(f.read())
Run Code Online (Sandbox Code Playgroud)
输出:
there is a lot of blah blah in this so-called file
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以创建一个临时文件并传递其名称以打开:
在Unix上:
tp = tempfile.NamedTemporaryFile()
tp.write(b'there is a lot of blah blah blah in this so-called file')
tp.flush()
open(tp.name, 'r')
Run Code Online (Sandbox Code Playgroud)
在Windows上,您需要先关闭临时文件,然后才能打开它:
tp = tempfile.NamedTemporaryFile(delete=False)
tp.write(b'there is a lot of blah blah blah in this so-called file')
tp.close()
open(tp.name, 'r')
Run Code Online (Sandbox Code Playgroud)
使用完后,您将负责删除该文件。