Python Forum
mass rename files in folders
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
mass rename files in folders
#1
hi all,

I got this code:

import os

def renamer(folder):
    dirname = folder
    files = os.listdir(folder)
    os.chdir(folder)
    for i in files:
        os.rename(i, dirname + '_' + i)


renamer('abc')
it works if I give an example folder to the function. But it doesnt work in a for cycle like this:

for i in os.listdir('.'):
    renamer(i)
i have tons of folders that contain video files like this: file-1.mp4, file-2.mp4, file-3.mp4, and I'd like the files renamed a way that the new filename would contain the parent directory's name included: abc_file-1.mp4

Could you please help me to fix this code?
Reply
#2
Which Python version you are using. os.scandir is much faster than os.listdir.

If 'i' happens to be a file you can't use os.listdir on it.

See os.walk
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
I use python 3.6, i modified the script, but it still doesnt work

import os

def renamer(*folder):
    dirname = folder
    files = os.listdir(folder)
    os.chdir(folder)
    for i in files:
        os.rename(i, dirname + '_' + i)



for root, dirs, files in os.walk('.'):
    dirs[:] = [d for d in dirs if not d[0] == '.']

    renamer(dirs)
Reply
#4
import os
from sys import argv

path = argv[1] # take the directory from the command line.
for root, dirs, files in os.walk(path):
    for file in files:
        dir = os.path.split(root)[-1]
        os.rename(file, f"{dir}-{file}")
os.walk starts from the 'path' and for each directory from the three returns a tuple:
{the_current_directory,
 a_list_of_all_directories_in_the_current_directory,
 a_list_of_all_files_in_the_current_directory)
So, you just pass the path to the os.walk and for each iteration, you change the names of the 'files' from the tuple (root, dirs, files). 'files' is a list of all files in 'root', which is the current directory during the scan.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#5
Your script makes hidden files from regular files:-) in current folder, and that
os.rename(file, f"{dir}-{file}")
is buggy, by the way it was a good idea to take the input folder as a command line argument.

mine is buggy still:

for root, folders, files in os.walk('test'):

    for file in files:
        folder = os.path.split(root)[1]

        src = file
        dst = folder + '_' + file

        os.rename(src, dst)
it complains:
FileNotFoundError: [Errno 2] No such file or directory: 'file-1.mp4' -> 'def_file-1.mp4'

It's crazy, if I replace os.rename(scr, dst) with print(src, dst), it finds the files:-)
Reply
#6
That is because the command line argument is '.' and as you may know the dot in the beginning of a file/dir name in *nix systems makes them hidden.
Change it like this:

import os
from sys import argv
 
path = os.path.abspath(argv[1])
for root, dirs, files in os.walk(path):
    for file in files:
        dir = os.path.split(root)[-1]
        os.rename(file, f"{dir}-{file}")


This change should make it works:
for root, folders, files in os.walk('test'):
 
    for file in files:
        folder = os.path.split(root)[1]
        file_name = f"{folder}_{file}"
        src = os.path.join(root, file_name)
        os.rename(src, dst)
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Using zipfile module - finding folders not files darter1010 2 248 Apr-06-2024, 07:22 AM
Last Post: Pedroski55
  Rename files in a folder named using windows explorer hitoxman 3 734 Aug-02-2023, 04:08 PM
Last Post: deanhystad
  Rename all files in a folder hitoxman 9 1,482 Jun-30-2023, 12:19 AM
Last Post: Pedroski55
  Create new folders and copy files cocobolli 3 1,443 Mar-22-2023, 10:23 AM
Last Post: Gribouillis
  Copy only hidden files and folders with rsync Cannondale 2 997 Mar-04-2023, 02:48 PM
Last Post: Cannondale
  How to do a mass replace within a CSV file? cubangt 9 5,352 May-09-2022, 06:52 PM
Last Post: snippsat
  Rename part of filename in multiple files atomxkai 7 7,328 Feb-18-2022, 10:03 PM
Last Post: atomxkai
  Rename Files based on XML file klturi421 3 2,181 Oct-22-2021, 07:37 PM
Last Post: klturi421
  Moving files to Folders giddyhead 13 9,127 Mar-07-2021, 02:50 AM
Last Post: giddyhead
  Rename Multiple files in directory to remove special characters nyawadasi 9 6,362 Feb-16-2021, 09:49 PM
Last Post: BashBedlam

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020