Python: how to replace spaces with an underscore in the name of ALL files, folders and subfolders?

How can we replace spaces in the names of folders, subfolders and files in this parent folder?

My initial attempt to replace to level 8 is given below. I am sure there are better ways. My code looks ugly. Better solutions are more than welcome.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#


def replace_space_by_underscore(path):
    """Replace whitespace in filenames by underscore."""
    import glob
    import os
    for infile in glob.glob(path):
        new = infile.replace(" ", "_")
        try:
            new = new.replace(",", "_")
        except:
            pass
        try:
            new = new.replace("&", "_and_")
        except:
            pass
        try:
            new = new.replace("-", "_")
        except:
            pass
        if infile != new:
            print(infile, "==> ", new)
        os.rename(infile, new)

if __name__ == "__main__":
    try:
        replace_space_by_underscore('*/*/*/*/*/*/*/*')
    except:
        pass
    try:
        replace_space_by_underscore('*/*/*/*/*/*/*')
    except:
        pass
    try:
        replace_space_by_underscore('*/*/*/*/*/*')
    except:
        pass
    try:
        replace_space_by_underscore('*/*/*/*/*')
    except:
        pass
    try:
        replace_space_by_underscore('*/*/*/*')
    except:
        pass
    try:
        replace_space_by_underscore('*/*/*')
    except:
        pass
    try:
        replace_space_by_underscore('*/*')
    except:
        replace_space_by_underscore('*')
+4
source share
3 answers

You can use os.walkone that allows you to change the names of iterated folders on the fly:

import os

def replace(parent):
    for path, folders, files in os.walk(parent):
        for f in files:
            os.rename(os.path.join(path, f), os.path.join(path, f.replace(' ', '_')))
        for i in range(len(folders)):
            new_name = folders[i].replace(' ', '_')
            os.rename(os.path.join(path, folders[i]), os.path.join(path, new_name))
            folders[i] = new_name

os.walk , parent . tuple (current path, list of files, list of folders). , os.walk .

:

.
├── new doc
└── sub folder
    ├── another folder
    ├── norename
    └── space here

:

.
├── new_doc
└── sub_folder
    ├── another_folder
    ├── norename
    └── space_here
+6

. ; ( ) X ( os.chdir(X)), ( os.chdir("..")).

+1

@niemmi, :

: script HOME - , RENAME , HIDDEN.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Date: Dec 15, 2016


def replace_space_by_underscore(parent):
    """Replace whitespace by underscore in all files and folders.

    replaces    , - [ ] () __   ==>  underscore

    """
    import os
    for path, folders, files in os.walk(parent):
        # rename the files
        for f in files:
            old = os.path.join(path, f)
            bad_chars = [r' ', r',', r'-', r'&', r'[', r']', r'(', r')', r'__']
            for bad_char in bad_chars:
                if bad_char in f:
                    new = old.replace(bad_char, '_')
                    print(old, "==>", new)
                    os.rename(old, new)

        # rename the folders
        for i in range(len(folders)):
            new_name = folders[i].replace(' ', '_')
            bad_chars = [r' ', r',', r'-', r'&',
                         r'[', r']', r'(', r')', r'__']
            for bad_char in bad_chars:
                if bad_char in new_name:
                    new_name = new_name.replace(bad_char, '_')
                    print(folders[i], "==> ", new_name)
            old = os.path.join(path, folders[i])
            new = os.path.join(path, new_name)
            os.rename(old, new)
            folders[i] = new_name


if __name__ == "__main__":
    replace_space_by_underscore('.')
+1

Source: https://habr.com/ru/post/1663905/


All Articles