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.
There is a
tempfilemodule for python, but a simple file creation also does the trick:Now you can write to it using the
writemethod:With the
tempfilemodule this might look like this:With
mkstempyou are responsible for deleting the file after you are done with it. With other arguments, you can influence the directory and name of the file.UPDATE
As rightfully pointed out by Emmet Speer, there are security considerations when using
mkstemp, as the client code is responsible for closing/cleaning up the created file. A better way to handle it is the following snippet (as taken from the link):The
os.fdopenwraps the file descriptor in a Python file object, that closes automatically when thewithexits. The call toos.removedeletes the file when no longer needed.