Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a tmp file in Python?

Tags:

python

I have this function that references the path of a file:

some_obj.file_name(FILE_PATH) 

where FILE_PATH is a string of the path of a file, i.e. H:/path/FILE_NAME.ext

I want to create a file FILE_NAME.ext inside my python script with the content of a string:

some_string = 'this is some content' 

How to go about this? The Python script will be placed inside a Linux box.

like image 533
SuperString Avatar asked Dec 20 '11 14:12

SuperString


People also ask

How do I create a TMP file?

To create and use a temporary file The application opens the user-provided source text file by using CreateFile. The application retrieves a temporary file path and file name by using the GetTempPath and GetTempFileName functions, and then uses CreateFile to create the temporary file.

What is TMP in Python?

Temporary files, or "tempfiles", are mainly used to store intermediate information on disk for an application. These files are normally created for different purposes such as temporary backup or if the application is dealing with a large dataset bigger than the system's memory, etc.

Where does Python store temporary files?

This function returns name of directory to store temporary files. 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.

How do you name a temporary file in Python?

You just want a file object (pointing to an empty file) which has a filename associated to it and hence you cannot use a StringIO object: from tempfile import NamedTemporaryFile f = NamedTemporaryFile() # use f .. Once f is garbage collected, or closed explicitly, the file will automatically be removed from disk.


1 Answers

I think you're looking for this: http://docs.python.org/library/tempfile.html

import tempfile with tempfile.NamedTemporaryFile() as tmp:     print(tmp.name)     tmp.write(...) 

But:

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

If that is a concern for you:

import os, tempfile tmp = tempfile.NamedTemporaryFile(delete=False) try:     print(tmp.name)     tmp.write(...) finally:     tmp.close()     os.unlink(tmp.name) 
like image 180
Minras Avatar answered Oct 01 '22 13:10

Minras