How to create a temporary files/directories with user defined names in python. I am aware of tempfile . However I couldn't see any function with filename as argument.
Note: I need this for unit testing the glob(file name pattern matching) functionality on a temporary directory containing temporary files rather than using the actual file system.
How are temporary files named? A temporary file name varies depending on the program and operating system used. For example, Microsoft Windows and Windows programs often create a file with a . tmp file extension as a temporary file.
Select the TEMP variable and then click the “Edit” button. In the Edit User Variable window, type a new path for the TEMP folder into the “Variable value” box.
Use mktemp -d . It creates a temporary directory with a random name and makes sure that file doesn't already exist. You need to remember to delete the directory after using it though.
If you need to name the temporary files AND directories it looks like you'll have to manage the names and/or creation/deletion yourself.
However, if you just need to control the names of the files you can use tempfile.TemporaryDirectory()
to create a temp directory, created your named files in that directory, and then it will all get deleted when it goes out of context.
Like this:
with tempfile.TemporaryDirectory() as temp_dir:
# open your files here
named_file = open(os.path.join(temp_dir.name, "myname.txt"), 'w')
# do what you want with file...
# directory and files get automatically deleted here...
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