Python equivalent of _tempnam?

Oktay Safak oktaysafak at ixir.com
Wed Apr 2 05:36:14 EST 2003


I use two functions like the ones below (slightly modified for general use):

def get_range(folder):
    import os
    folderlist = os.listdir(folder)

    if len(folderlist) == 0:
        return ([], []) # Empty folder
    else:
        existing_list = []
        for item in folderlist:
            # get the file name without path and ext.,
            # extract the number from filename and append to existing_list

existing_list.append(extract_number(os.path.split(os.path.splitext(item)[0])
[1]))

            check_list = [f for f in range(min(existing_list),
max(existing_list)+1)]
            missing_list = [f for f in check_list if f not in existing_list]

            return existing_list, missing_list

def extract_number(filename):
    """Very simple minded solution, assumes that filename
       is in *****123.*** form, * being non-numeric."""
    import string
    num = ""
    for char in filename:
        if char in string.digits:
            num += char
    return int(num) # required for number comparisons!

The first function gives you the list of existing files and the missing ones
in that range. All you have to do then is to use
int(max(get_range(folder)[0]))+1 for your next file number.

Note that these are quick hacks just to get the work done, not works of art.
Be careful about exceptions and make sure you handle them properly. Also,
when you have too much files in your folder (I mean thousands!) this
approach gets verrry slow! Then maybe you should start considering keeping
an index about the files in the folder.

Hope this helps.


----- Original Message -----
From: "Richard" <richardd at hmgcc.gov.uk>
Newsgroups: comp.lang.python
To: <python-list at python.org>
Sent: Wednesday, April 02, 2003 12:58 PM
Subject: Python equivalent of _tempnam?


> Hi,
>
> I am writing an application which produces file output. Files are
outputted
> to a directory and I want to ensure that if an output filename is given
that
> already exists in that directory a number is affixed to the filename to
> ensure that the existing file is not appended to or overwritten. i.e.
> output_0.txt, then output_1.txt etc...
>
> I have been told that a way of doing this in C is by using _tempnam( ).
> However I want to write this in Python, so is there an equivalent
function?
> My application will only be executed occasionally so I am unable to keep
an
> internal record of file numbering. I assume that I need to find the
highest
> number file (if exists) in the directory and then increment that by one
> before creating the new file.
>
> Any ideas?
>
> Cheers
>
> Richard
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>






More information about the Python-list mailing list