Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

temp files/directories with custom names?

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.

like image 581
hello world Avatar asked Sep 20 '16 11:09

hello world


People also ask

How are temporary files named?

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.

How do I rename my temp folder?

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.

How do I create a tmp folder?

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.


1 Answers

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...
like image 59
j314erre Avatar answered Oct 03 '22 22:10

j314erre