简体   繁体   English

如何将文件写入 memory 文件路径并从 Python 中的 memory 文件路径读取?

[英]How to write file to memory filepath and read from memory filepath in Python?

An existing Python package requires a filepath as input parameter for a method to be able to parse the file from the filepath.现有的 Python package 需要文件路径作为输入参数,以便能够从文件路径解析文件的方法。 I want to use this very specific Python package in a cloud environment, where I can't write files to the harddrive.我想在无法将文件写入硬盘的云环境中使用这个非常具体的 Python package。 I don't have direct control over the code in the existing Python package, and it's not easy to switch to another environment, where I would be able to write files to the harddrive.我无法直接控制现有 Python package 中的代码,并且切换到另一个环境并不容易,在那里我可以将文件写入硬盘驱动器。 So I'm looking for a solution that is able to write a file to a memory filepath, and let the parser read directly from this memory filepath.因此,我正在寻找一种能够将文件写入 memory 文件路径并让解析器直接从此 memory 文件路径读取的解决方案。 Is this possible in Python?这在 Python 中是否可行? Or are there any other solutions?或者还有其他解决方案吗?

Example Python code that works by using harddrive, which should be changed so that no harddrive is used:使用硬盘驱动器工作的示例 Python 代码,应更改为不使用硬盘驱动器:

temp_filepath = "./temp.txt"
with open(temp_filepath, "wb") as file:
  file.write("some binary data")
model = Model()
model.parse(temp_filepath)

Example Python code that uses memory filesystem to store file, but which does not let parser read file from memory filesystem:示例 Python 代码使用 memory 文件系统存储文件,但不允许解析器从 memory 文件系统读取文件:

from fs import open_fs
temp_filepath = "./temp.txt"
with open_fs('osfs://~/') as home_fs:
  home_fs.writetext(temp_filepath, "some binary data")
model = Model()
model.parse(temp_filepath)

You're probably looking for StringIO or BytesIO from io您可能正在寻找来自StringIOioBytesIO

import io

with io.BytesIO() as tmp:
    tmp.write(content)
    # to continue working, rewind file pointer
    tmp.seek(0)
    # work with tmp 

pathlib may also be an advantage pathlib也可能是一个优势

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM