How to Create an Incrementing Filename in Python

Incrementing a file name in python

I strongly recommend you to use pathlib instead of os.path.join. This is more convenient.

def incrementfile():
td = datetime.datetime.today().date()
path = pathlib.Path("/tmp") #set your output folder isntead of /tmp
inc = len(list(path.glob(f"{td}*")))+1
outfile = path/f"{td}_{inc}.txt"
return outfile

How do you increment file name in Python

for i in range(10):
filename = 'data_%d.dat'%(i,)
print filename

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 generate auto increment in a folder in python?

It sounds like the biggest problem you're having is that each button click is re-starting the execution of your python script, so using a global variable won't work since that doesn't persist across executions. In this case, I'd suggest using something like the pickle module to store and reload your counter value each time you execute your script. Using that module, your solution could look something like this:

import pickle
from pathlib import Path

# creates file if it doesn't exist
myfile = Path("save.p")
myfile.touch(exist_ok=True)

persisted = {}
with (open(myfile, "rb")) as f:
try:
persisted = pickle.load(f)
except EOFError:
print("file was empty, nothing to load")

# use get() to avoid KeyError if key doesn't exist
if persisted.get('counter') is None:
persisted['counter'] = 1

wb.save(f"invoice/B{persisted.get('counter')}.xlsx")
persisted['counter'] += 1

# save everything back into the same file to be used next execution
pickle.dump(persisted, open(myfile, "wb"))

BONUS: If you want the count to be padded with zeros in the filename, use persisted.get('counter'):05d in the curly brackets when saving the file. The 5 indicates you want the resulting value to be at least 5 characters long, so for example 2 would become 00002 and 111 would become 00111.

Auto-increment file name Python

While I wouldn't recommend using recursion for this (python's stack maxes out at about 1000 function calls deep), you're just missing a return for the recursive bit:

new_name= os.path.join(os.path.split(old_name)[0],”output_” + os.path.split(old_name)[1])
checkfile(0,new_name,old_name)

Should instead be:

new_name= os.path.join(os.path.split(old_name)[0],”output_” + os.path.split(old_name)[1])
return checkfile(ii,new_name,old_name)

But really, you can make this a whole lot simpler by re-writing it as:

 def checkfile(path):
path = os.path.expanduser(path)

if not os.path.exists(path):
return path

root, ext = os.path.splitext(os.path.expanduser(path))
dir = os.path.dirname(root)
fname = os.path.basename(root)
candidate = fname+ext
index = 0
ls = set(os.listdir(dir))
while candidate in ls:
candidate = "{}_{}{}".format(fname,index,ext)
index += 1
return os.path.join(dir,candidate)

This form also handles the fact that filenames have extensions, which your original code doesn't, at least not very clearly. It also avoids needless os.path.exist's, which can be very expensive, especially if the path is a network location.

Python: Create new files with two parts incrementing names based on user input

Here is a very simple answer and you can customize it too.

def CreateFile(filerange, filename, extension_name, extension_length):
for i in range(0, filerange):
for j in range(0, extension_length):
f = open(f"{filename}{i+1}_{extension_name}{j+1}.txt", "a")
f.write("You can add here your text or customize as per your needs")
f.close()

CreateFile(2, 'T', 'S', 4)

Hope This help you:

filerange -> no of files you need eg:2 files T1,T2
filename -> Should be your filename eg:T
extension_name -> eg:S
extension_length -> eg:S1,S2,S3,S4

Here is the output:

T1_S1.txt
T1_S2.txt
T1_S3.txt
T1_S4.txt
T2_S1.txt
T2_S2.txt
T2_S3.txt
T2_S4.txt

Pandas: Need to increment duplicate file names starting at 1

Try:

numbered = df_files["Filestub"] + "_" + df_files.groupby("Filestub").cumcount().add(1).astype(str).str.zfill(3) + df_files["ext"]

df["NumberedCopy"] = numbered.where(df_files["Filestub"].duplicated(keep=False), df_files["filename"])

>>> df_files
ID filename ext Filestub NumberedCopy
0 1000 filename.pdf .pdf filename filename_001.pdf
1 1001 filename.pdf .pdf filename filename_002.pdf
2 1002 a_file.txt .txt a_file a_file_001.txt
3 1003 a_file.txt .txt a_file a_file_002.txt
4 1004 a_file.txt .txt a_file a_file_003.txt

While loop for incrementing file name value

If you want to create files with increasing numbers like e.g. Windows does when copying a file with the same name, replace your os.rename() with following function:

def moveIncrementing(source, destination):
i = 0
while True:
try:
return os.rename(source, f"{destination}_{i}" if i else destination)
except OSError as ex:
i+=1
print(ex)

It will keep trying to move the files until operation passes successfully. Just a warning, it will add numbers AFTER the file extension, so the files won't be properly recognized by their extension. But that's an excercise I'm leaving for you.



Related Topics



Leave a reply



Submit