Python Forum

Full Version: how to increment all file names in a folder
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
how do i create a short script to change all file names in a folder with an increment?

is there a guide or a simple rule?

want to use it as a practice for coding with python i am a beginner
You want the os module. It has a rename function for renaming files, and a listdir function for finding the files in a folder (or a walk function for doing it recursively). The re module could be helpful for finding the index in the file name, you could do it with the isdigit method of strings. Or if it's consistently the same number of digits at the end of a file, you could just use slicing.
Can pick up some tips in this recent post.
You can also look into pathlib,it's a new way to handle filesystem paths ect...
are the file names just numbers like "12345678" or do they partly have numbers like "data2018"?
(Sep-09-2018, 06:43 AM)Skaperen Wrote: [ -> ]are the file names just numbers like "12345678" or do they partly have numbers like "data2018"?
All the files in the folder got the exact same name which is a pain to work with, there are thousands of them so I probably need to use a loop right?

I need it to automatically go from file to file and add a number to each of them like so:
file.

file1.

file2.

and so on...
so you need to make a mass rename. yeah that obviously needs a loop. you could write a script to do it. you could do it in Python, but in a shell script might be easier if you know shell scripting. you could do it in Python as a learning exercise. me, personally, i'd do it in a command (in bash) in that directory like:

(ls -1|while read f;do mv $f ${f}1;done)

if you want the "1" to be before the "." it will be a slightly longer command. but maybe it is better for you to do this as a Python script. write something that outputs the commands to do it and when it makes all the right commands then pipe them into a shell.