Is it possible to get the path of a tempfile in Python 3

狂风中的少年 提交于 2020-04-12 16:47:00

问题


I was wondering if it was possible to get the file path of a temporary file made using the tempfile library. Basically, I'm trying to make a function that intakes some data, and generates a temporary csv file based off of said data. I was wondering if there was a way to get the path of this temporary file?


回答1:


Use tempfile.NamedTemporaryFile to create a temporary file with a name, and then use the .name attribute of the object.

Note that there are platform-specific limitations on how this name can be used. The documentation says:

Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later).




回答2:


tempfile.NamedTemporaryFile has a .dir property which will give you want you want.


EDIT: No, it is not .name, @Barmar, but looking through the source code for tempfile, I don't see a .dir property either. However, you can use the .name property in conjunction with os.path's dirname method as follows:

with tempfile.NamedTemporaryFile(suffix='.csv', prefix=os.path.basename(__file__)) as tf:
    tf_directory = os.path.dirname(tf.name)



回答3:


Anyway, if you need the path of the tempfile directory you can use tempfile.gettempdir()



来源:https://stackoverflow.com/questions/51110783/is-it-possible-to-get-the-path-of-a-tempfile-in-python-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!