JR Santos
JR Santos

Reputation: 145

Rename with Counter using Python

I would like to mention that pretty much all of these answers worked well to controlling what it renames, I wanted to place a check on all that worked, only one answer did not work, but if this helps anyone, they will have 3 out of 4 answers that works

My shared script works great, but it renames everything it finds in the directory so please be careful when using my shared script
for super large files I use this python

import os
# Function to rename multiple files
def main():
   i = 1000
   path="C:/Users/user/Desktop/My Folder/New folder/New folder/"
   for filename in os.listdir(path):
      my_dest ="(" + str(i) + ")" + ".txt"
      my_source =path + filename
      my_dest =path + my_dest
      # rename() function will
      # rename all the files
      os.rename(my_source, my_dest)
      i += 1
# Driver Code
if __name__ == '__main__':
   # Calling main() function
   main()

OK, so I am trying to control the counter to only see txt files, if I have .txt, .jpeg, .mpeg,
everything gets rename, how can I control this to only .txt files

One more problem, when I use this Python counter or a batch counter it flips my file names

Example

File_2019.txt - this should be renamed to (1000).txt
FileRecycled_2019.txt - this should be renamed to (1001).txt

Outcome

FileRecycled_2019.txt - this should be renamed to (1000).txt
File_2019.txt - this should be renamed to (1001).txt

When using this method based on filename it flips the order of my files
It takes it out of alphabetical order

I am working on a solution for the names being flipped once I find it I will share it so if it helps others

OK, so I have a underscore remover batch file, and that fixed the flipping
and it renames correctly
for smaller files I will use this

@echo off
Setlocal enabledelayedexpansion

Set "Pattern=_"
Set "Replace= "

For %%a in (*.txt) Do (
    Set "File=%%~a"
    Ren "%%a" "!File:%Pattern%=%Replace%!"
)

set count=1000
for %%f in (*.txt) do (
  set /a count+=1
  ren "%%f" "(!count!).txt"
)

Upvotes: 2

Views: 1048

Answers (4)

mo1ein
mo1ein

Reputation: 605

I solved it an easy way:

import os
# Function to rename multiple files
def main():
   i = 1000
   path = 'C:/Users/user/Desktop/My Folder/New folder/New folder/'
   for filename in os.listdir(path):
      my_dest = f'({str(i)}).txt'
      my_dest = path + my_dest
      my_source = path + filename
      ext = my_source.split('.')[-1]
      if ext == 'txt':
          os.rename(my_source, my_dest)
          i += 1
# Driver Code
if __name__ == '__main__':
   # Calling main() function
   main()

Upvotes: 1

Comsavvy
Comsavvy

Reputation: 770

You can accomplish this by using the pathlib module

from pathlib import Path
from os import chdir
path = Path.home() / 'desktop' / 'My Folder' / 'New folder' / 'New folder'  # The path to use
to_usenum = 1000  # Start num
alltxt = list(path.glob('*.txt'))  # Getting all the txt files
chdir(path)  # Changing the cwd to the path

for i, txtfile in enumerate(alltxt):
    to_usename = f"({to_usenum+i}).txt"  # The name to use
    txtfile.rename(to_usename) 

The pathlib module comes in handy when it comes to files handling. The os module was used in the code to change the current working directory to the path's location because the renamed file will be placed in the current working directory.

Upvotes: 1

chsws
chsws

Reputation: 443

You could check the filename has .txt before renaming.

if filename.endswith(".txt"):
    os.rename(my_source, my_dest)
    i += 1

On the filenames, you haven't specified an order for the names. You could use for filename in sorted(os.listdir(path)): to move through in alphabetical order.

My solution would be:

import os
import glob

def main():
    path = "C:/Users/user/Desktop/My Folder/New folder/New folder/"
    suffix = '.txt'
    files = glob.glob(path + '*' + suffix)
    for idx, filename in enumerate(sorted(files)):
        os.rename(
            filename,
            os.path.join(path, f"({1000 + idx})" + suffix)
        )

if __name__=="__main__":
    main()

This uses glob to get all file paths in the folder with .txt suffix. It also uses enumerate to count each file rather than having to count the i value yourself. The file name is generated using an f-string.

Upvotes: 1

fthomson
fthomson

Reputation: 789

my suggestion would be to use glob, give it a go

import os
import glob
# Function to rename multiple files
def main():
    i = 1000
    path="C:/Users/user/Desktop/My Folder/New folder/New folder/"
    files = glob.glob(path + '*.txt')
    for filename in files:
        my_dest ="(" + str(i) + ")" + ".txt"
        my_source =path + filename
        my_dest =path + my_dest
        # rename() function will
        # rename all the files
        os.rename(my_source, my_dest)
        i += 1
# Driver Code
if __name__ == '__main__':
   # Calling main() function
   main()

this will search for any file name ending with txt extension

Upvotes: 0

Related Questions