Python Forum
how to increment all file names in a folder - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: how to increment all file names in a folder (/thread-12699.html)



how to increment all file names in a folder - SoulsKeeper - Sep-08-2018

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


RE: how to increment all file names in a folder - ichabod801 - Sep-08-2018

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.


RE: how to increment all file names in a folder - snippsat - Sep-08-2018

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...


RE: how to increment all file names in a folder - Skaperen - Sep-09-2018

are the file names just numbers like "12345678" or do they partly have numbers like "data2018"?


RE: how to increment all file names in a folder - SoulsKeeper - Sep-09-2018

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


RE: how to increment all file names in a folder - Skaperen - Sep-10-2018

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.