gpt4 book ai didi

python - 在python中将字符串视为文件

转载 作者:太空狗 更新时间:2023-10-30 00:31:12 25 4
gpt4 key购买 nike

为了重写开源库,我想在 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')

到目前为止我尝试了什么

  1. 我研究了 StringIO 并尝试将其用作类似路径的对象而不是骰子:
    导入字符串IO
    输出 = StringIO.StringIO()
    output.write('第一行.\n')
    file_ptr = open(输出,'r')
    嗯,这行不通,因为 StringIO 不是类路径对象。

  2. 我以类似的方式尝试过 tempfile 但没有成功。
    导入临时文件
    tp = tempfile.TemporaryFile()
    tp.write(b'这个所谓的文件里有很多废话')
    打开(tp,'r')

  3. 最后,我尝试了 mmap 以查看是否可以将字符串写入内存,然后使用 open 打开内存指针,但没有成功。

感谢任何帮助! :-)

编辑 1:我正在考虑如何解决问题

如果PurePathpathlib.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'

最佳答案

StringIO 返回一个StringIO 对象,它几乎等同于open 语句返回的文件对象。所以基本上,您可以使用 StringIO 代替 open 语句。

# from StringIO import StringIO  # for Python 2, old
from io import StringIO
with StringIO('there is a lot of blah blah in this so-called file') as f:
print(f.read())

输出:

there is a lot of blah blah in this so-called file

关于python - 在python中将字符串视为文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44381249/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com