Make a unique filesystem path, without creating the file

Oscar Benjamin oscar.j.benjamin at gmail.com
Wed Feb 17 08:31:22 EST 2016


On 16 February 2016 at 19:40, Ben Finney <ben+python at benfinney.id.au> wrote:
> Oscar Benjamin <oscar.j.benjamin at gmail.com> writes:
>
>> If you're going to patch open to return a fake file when asked to open
>> fake_file_path why do you care whether there is a real file of that
>> name?
>
> I don't, and have been saying explicitly many times in this thread that
> I do not care whether the file exists. Somehow that is still not clear?


Sorry Ben I misunderstood. I think I can see the source of confusion
which is in your first message:
"""
In some code (e.g. unit tests) I am calling ‘tempfile.mktemp’ to
generate a unique path for a filesystem entry that I *do not want* to
exist on the real filesystem.
"""
I read that as meaning that it was important that the file did not
exist. But you say that you don't care if the file actually exists in
the filesystem or not and just want a unique path.

What do you mean by unique here? The intention of mktemp is that the
path is unique so that there would not exist a file of that name and
if you opened it for writing you wouldn't be interfering with any
existing file. Do you just mean a function that returns a different
value each time it's called? How about this:

count = 0
def unique_path():
    global count
    count += 1
    return os.path.join(tempfile.gettempdir(), str(count))

--
Oscar



More information about the Python-list mailing list