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.
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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With