Create file but if name exists add number
In a way, Python has this functionality built into the tempfile
module. Unfortunately, you have to tap into a private global variable, tempfile._name_sequence
. This means that officially, tempfile
makes no guarantee that in future versions _name_sequence
even exists -- it is an implementation detail.
But if you are okay with using it anyway, this shows how you can create uniquely named files of the form file#.pdf
in a specified directory such as /tmp
:
import tempfile
import itertools as IT
import os
def uniquify(path, sep = ''):
def name_sequence():
count = IT.count()
yield ''
while True:
yield '{s}{n:d}'.format(s = sep, n = next(count))
orig = tempfile._name_sequence
with tempfile._once_lock:
tempfile._name_sequence = name_sequence()
path = os.path.normpath(path)
dirname, basename = os.path.split(path)
filename, ext = os.path.splitext(basename)
fd, filename = tempfile.mkstemp(dir = dirname, prefix = filename, suffix = ext)
tempfile._name_sequence = orig
return filename
print(uniquify('/tmp/file.pdf'))
How to create a file with '01' if name exists?
I have found a solution, Thanks!!
b = True
c = 1
while b:
f_name = 'Task-{:02.0f}.txt'.format(c)
try:
f = open(f_name,'x')
b = False
except FileExistsError:
c += 1
f.close()
How to increment the filename number if the file exists
This problem is to always initialize num = 0
, so if file
exists, it saves file0.jpg
and does not check whether file0.jpg
exists.
So, to code work. You should check until it is available:
int num = 0;
String save = at.getText().toString() + ".jpg";
File file = new File(myDir, save);
while(file.exists()) {
save = at.getText().toString() + (num++) + ".jpg";
file = new File(myDir, save);
}
Create new file but add number if filename already exists in bash
The following script can help you. You should not be running several copies of the script at the same time to avoid race condition.
name=somefile
if [[ -e $name.ext || -L $name.ext ]] ; then
i=0
while [[ -e $name-$i.ext || -L $name-$i.ext ]] ; do
let i++
done
name=$name-$i
fi
touch -- "$name".ext
Check if File Exists and then append Number to Name
@echo off
setlocal
set "dir=C:\...\myFolder\"
set "i=0"
:get_filename
Set /a "i+=1"
if exist "%dir%Traces%i%.txt" goto :get_filename
set "filename=Traces%i%.txt"
echo "%dir%%filename%"
endlocal
pause
Can just use goto
a label to loop to get an indexed filename. Once the 1st indexed filename is not found, filename
is set with the value of the indexed filename available for creation. How to create a new file with additional incrementing number when file already exists?
Working Code:
String fileName = "test.txt";
String extension = "";
String name = "";
int idxOfDot = fileName.lastIndexOf('.'); //Get the last index of . to separate extension
extension = fileName.substring(idxOfDot + 1);
name = fileName.substring(0, idxOfDot);
Path path = Paths.get(fileName);
int counter = 1;
File f = null;
while(Files.exists(path)){
fileName = name+"("+counter+")."+extension;
path = Paths.get(fileName);
counter++;
}
f = new File(fileName);
Explanation:Firstly separate
extension
andfile name without extension
and setcounter=1
then check if this file exists or not. If exists go to step 2 otherwise got to step 3.If file exists then generate new name with
file name without extension
+(
+counter
+)
+extension
and check this file exists or not. If exists then repeat this step with incrementcounter
.Here create file with latest generated file name.
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 :) How to increment the filename if file already exists in javascript
You can check this.state.Files
before. A recursive function could be used here. Imagine you load a file named export.csv
. The second one would export.csv
transformed in export_1.csv
. But on a third one named export.csv
, the verification would be done on export
, leading to export_1
=> Error !
The best is to do :
const checkNameOfTheFile = (newFileName) => {
// Ex 'export.csv'
const counter = this.state.Files.filter(f => f.fileName === newFileName).length;
// If counter >= 2, an error has already been passed to the files because it means
// 2 files have the same name
if (counter >= 2) {
throw 'Error duplicate name already present';
}
if (counter === 0) {
return newFileName
}
if (counter === 1) {
const newName = `${newFileName.split('.')[0]}_${counter}.${newFileName.split('.')[1]}`;
// Return export_1.csv;
return checkNameOfTheFile(newName);
// We need to check if export_1.csv has not been already taken.
// If so, the new name would be export_1_1.csv, not really pretty but it can be changed easily in this function
}
};
const CompleteData= {
fileData: reader.result,
fileName: checkNameOfTheFile(file.name),
};
Increment the filename if it already exists when saving files in node.js?
I use something similar to version uploaded image files on disk. I decided to use the "EEXIST" error to increment the number rather than explicitly iterating the files in the directory.
const writeFile = async(filename, data, increment = 0) => {
const name = `${path.basename(filename, path.extname(filename))}${increment || ""}${path.extname(filename)}`
return await fs.writeFile(name, data, { encoding: 'utf8', flag: 'wx' }).catch(async ex => {
if (ex.code === "EEXIST") return await writeFile(filename, data, increment += 1)
throw ex
}) || name
}
const unversionedFile = await writeFile("./file.txt", "hello world")
const version1File = await writeFile("./file.txt", "hello world")
const version2File = await writeFile("./file.txt", "hello world")
Related Topics
Setting Up S3 for Logs in Airflow
Appending to the Same List from Different Processes Using Multiprocessing
Difference Between Variable and Get_Variable in Tensorflow
Importerror: Cannot Import Name Numpy_Mkl
Matplotlib Custom Marker/Symbol
Python, Default Keyword Arguments After Variable Length Positional Arguments
Python Using Variables from Another File
How to Concatenate Three Excels Files Xlsx Using Python
How to Delete Created Variables, Functions, etc from the Memory of the Interpreter
Numpy Argsort - What Is It Doing
Pandas Number Rows Within Group in Increasing Order
Why Is True Returned When Checking If an Empty String Is in Another
Download Image File from the HTML Page Source
Converting Strings to Floats in a Dataframe
How to Concatenate Element-Wise Two Lists in Python