I have a python web form with two options - File upload and textarea. I need to take the values from each and pass them to another command-line program. I can easily pass the file name with file upload options, but I am not sure how to pass the value of the textarea.
I think what I need to do is:
I am not sure how to generate a unique file name. Can anybody give me some tips on how to generate a unique file name? Any algorithms, suggestions, and lines of code are appreciated.
Thanks for your concern
If you would like to have the datetime,hours,minutes etc..you can use a static variable. Append the value of this variable to the filename. You can start the counter with 0 and increment when you have created a file. This way the filename will surely be unique since you have seconds also in the file.
To create a file if not exist in Python, use the open() function. The open() is a built-in Python function that opens the file and returns it as a file object. The open() takes the file path and the mode as input and returns the file object as output.
I didn't think your question was very clear, but if all you need is a unique file name...
import uuid unique_filename = str(uuid.uuid4())
If you want to make temporary files in Python, there's a module called tempfile in Python's standard libraries. If you want to launch other programs to operate on the file, use tempfile.mkstemp() to create files, and os.fdopen() to access the file descriptors that mkstemp() gives you.
Incidentally, you say you're running commands from a Python program? You should almost certainly be using the subprocess module.
So you can quite merrily write code that looks like:
import subprocess import tempfile import os (fd, filename) = tempfile.mkstemp() try: tfile = os.fdopen(fd, "w") tfile.write("Hello, world!\n") tfile.close() subprocess.Popen(["/bin/cat", filename]).wait() finally: os.remove(filename)
Running that, you should find that the cat
command worked perfectly well, but the temporary file was deleted in the finally
block. Be aware that you have to delete the temporary file that mkstemp() returns yourself - the library has no way of knowing when you're done with it!
(Edit: I had presumed that NamedTemporaryFile did exactly what you're after, but that might not be so convenient - the file gets deleted immediately when the temp file object is closed, and having other processes open the file before you've closed it won't work on some platforms, notably Windows. Sorry, fail on my part.)
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