How Would You Make a Unique Filename by Adding a Number

How would you make a unique filename by adding a number?

Lots of good advice here. I ended up using a method written by Marc in an answer to a different question. Reformatted it a tiny bit and added another method to make it a bit easier to use "from the outside". Here is the result:

private static string numberPattern = " ({0})";

public static string NextAvailableFilename(string path)
{
// Short-cut if already available
if (!File.Exists(path))
return path;

// If path has extension then insert the number pattern just before the extension and return next filename
if (Path.HasExtension(path))
return GetNextFilename(path.Insert(path.LastIndexOf(Path.GetExtension(path)), numberPattern));

// Otherwise just append the pattern to the path and return next filename
return GetNextFilename(path + numberPattern);
}

private static string GetNextFilename(string pattern)
{
string tmp = string.Format(pattern, 1);
if (tmp == pattern)
throw new ArgumentException("The pattern must include an index place-holder", "pattern");

if (!File.Exists(tmp))
return tmp; // short-circuit if no matches

int min = 1, max = 2; // min is inclusive, max is exclusive/untested

while (File.Exists(string.Format(pattern, max)))
{
min = max;
max *= 2;
}

while (max != min + 1)
{
int pivot = (max + min) / 2;
if (File.Exists(string.Format(pattern, pivot)))
min = pivot;
else
max = pivot;
}

return string.Format(pattern, max);
}

Only partially tested it so far, but will update if I find any bugs with it. (Marcs code works nicely!) If you find any problems with it, please comment or edit or something :)

Create unique filename by adding incremental number

In order to do that, you must loop the filenames.

$month = "January"

For $i = 0 To 1000 ;max file versions is set to 1000

If $i = 0 Then
$num = ''
Else
$num = $i
EndIf

If Not FileExists("Emissions Log - " & $month & $num & ".csv") then
$file = FileOpen("Emissions Log - " & $month & $num & ".csv", 1)
ExitLoop
EndIf
Next

Is there an R function/loop that can add a unique number or string to a filename?

Suppose I have a directory like this:

/Documents (R home)
|
|-- my_data
|
|--data_1.Rda
|--data_2.Rda

Then I can list the files in the my_data directory with:

list.files(path.expand("~/my_data/"))
#> [1] "data_1.Rda" "data_2.Rda"

And I can generate the "next" Rda file path with a simple function:

next_rda <- function() {
f <- list.files(path.expand("~/my_data/"), pattern = "^data_\\d+\\.Rda")
num <- max(as.numeric(gsub("^data_(\\d)\\.Rda", "\\1", f)) + 1)
paste0(path.expand("~/my_data/data_"), num, ".Rda")
}

So that I can do:

next_rda()
#> [1] "C:/Users/Administrator/Documents/my_data/data_3.Rda"

This means if I want to save an object I can do:

save(obj, file = next_rda())

Which will save to the next incremental file. Since the function checks the directory each time, it always writes to a new file, numbered appropriately.

How to Generate unique file names in C#

If readability doesn't matter, use GUIDs.

E.g.:

var myUniqueFileName = string.Format(@"{0}.txt", Guid.NewGuid());

or shorter:

var myUniqueFileName = $@"{Guid.NewGuid()}.txt";

In my programs, I sometimes try e.g. 10 times to generate a readable name ("Image1.png"…"Image10.png") and if that fails (because the file already exists), I fall back to GUIDs.

Update:

Recently, I've also use DateTime.Now.Ticks instead of GUIDs:

var myUniqueFileName = string.Format(@"{0}.txt", DateTime.Now.Ticks);

or

var myUniqueFileName = $@"{DateTime.Now.Ticks}.txt";

The benefit to me is that this generates a shorter and "nicer looking" filename, compared to GUIDs.

Please note that in some cases (e.g. when generating a lot of random names in a very short time), this might make non-unique values.

Stick to GUIDs if you want to make really sure that the file names are unique, even when transfering them to other computers.

What is the best way to generate a unique and short file name in Java

Well, you could use the 3-argument version: File.createTempFile(String prefix, String suffix, File directory) which will let you put it where you'd like. Unless you tell it to, Java won't treat it differently than any other file. The only drawback is that the filename is guaranteed to be at least 8 characters long (minimum of 3 characters for the prefix, plus 5 or more characters generated by the function).

If that's too long for you, I suppose you could always just start with the filename "a", and loop through "b", "c", etc until you find one that doesn't already exist.

Python: How to create a unique file name?

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())

Safe to use random numbers to make filenames unique?

I just wanted to know if using this method to generate unique filenames is a good idea?

No. Uniqueness isn't a property of randomness. Random means that the resulting value is not in any way dependent upon previous state. Which means repeats are possible. You could get the same number many times in a row (though it's unlikely).

If you want values which are unique, use a GUID:

Guid.NewGuid();

As pointed out in the comments below, this solution isn't perfect. But I contend that it's good enough for the problem at hand. The idea is that Random is designed to be random, and Guid is designed to be unique. Mathematically, "random" and "unique" are non-trivial problems to solve.

Neither of these implementations is 100% perfect at what it does. But the point is to simply use the correct one of the two for the intended functionality.

Or, to use an analogy... If you want to hammer a nail into a piece of wood, is it 100% guaranteed that the hammer will succeed in doing that? No. There exists a non-zero chance that the hammer will shatter upon contacting the nail. But I'd still reach for the hammer rather than jury rigging something with the screwdriver.

How to create a file with unique name?

Since you've tagged the question gnu and linux, you can use the mkstemp() fucntion:

DESCRIPTION

The mkstemp() function generates a unique temporary filename from
template, creates and opens the file, and returns an open file
descriptor for the file.

The last six characters of template must be "XXXXXX" and these are
replaced with a string that makes the filename unique. Since it will
be modified, template must not be a string constant, but should be
declared as a character array.

For example:

char newFileName[] = "/path/to/new/file/someName.XXXXXX";
int newFileDescriptor = mkstemp( newFileName );

There are several other variations of the mkstemp() function on the man page that might fit your actual needs better.

Depending on how secure your file creation process has to be, creating a hopefully-unique name for the new file and then making sure that the file you open is actually the new file you meant to create and not some other file swapped in by malicious code is not easy to do securely - there have been quite a few exploits that use the inherent race condition between code generating a name and then trying to create the new file to break into a system or otherwise compromise it.

And be aware that such constructs as UUIDs are not really guaranteed to be unique. If they're just random numbers, they can obviously not be guaranteed to be unique (although the odds of a collision may be vanishingly small). If they're not truly random numbers, they have a pattern that can be predicted and exploited by malicious code.

If security is a requirement, you'd do best to use the operating system's facilities for creating a new, unique file and giving your code an open file descriptor or handle to that new file.

C#: What is the fastest way to generate a unique filename?

A GUID would be extremely fast, since it's implementation guarantees Windows can generate at least 16,384 GUIDS in a 100-nanosecond timespan. (As others pointed out, the spec doesn't guarantee, only allows for. However, GUID generation is really, really fast. Really.) The likelihood of collision on any filesystem anywhere on any network is very low. It's safe enough that although it'd be best practice to always check to see if that filename is available anyway, in reality you would never even need to do that.

So you're looking at no I/O operations except the save itself, and <0.2 milliseconds (on a test machine) to generate the name itself. Pretty fast.



Related Topics



Leave a reply



Submit