Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 562
Keyadun Avatar asked Jun 30 '18 00:06

Keyadun


People also ask

How do I get the file path of a text file in Python?

In order to obtain the Current Working Directory in Python, use the os. getcwd() method. This function of the Python OS module returns the string containing the absolute path to the current working directory.

Where is my python TEMP folder?

This name is generally obtained from tempdir environment variable. On Windows platform, it is generally either user/AppData/Local/Temp or windowsdir/temp or systemdrive/temp. On linux it normally is /tmp. This directory is used as default value of dir parameter.

Is Tempfile included in Python?

Python provides a module known as tempfile, which makes creating and handling temporary files easier. This module provides a few methods to create temporary files and directories in different ways. tempfile comes in handy whenever you want to use temporary files to store data in a Python program.


3 Answers

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).

like image 154
Barmar Avatar answered Sep 16 '22 14:09

Barmar


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) 
like image 32
hd1 Avatar answered Sep 16 '22 14:09

hd1


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

like image 42
Papageno Avatar answered Sep 19 '22 14:09

Papageno