Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/cmake/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:如何在所有文件、文件夹和子文件夹的名称中用下划线替换空白?_Python_Batch Rename - Fatal编程技术网

Python:如何在所有文件、文件夹和子文件夹的名称中用下划线替换空白?

Python:如何在所有文件、文件夹和子文件夹的名称中用下划线替换空白?,python,batch-rename,Python,Batch Rename,如何替换给定父文件夹中文件夹、子文件夹和文件名称中的空格 下面给出了我最初尝试更换到8级的情况。我相信有更好的办法。我的代码看起来很难看。 更好的解决方案非常受欢迎 #!/usr/bin/env python3 # -*- coding: utf-8 -*- # def replace_space_by_underscore(path): """Replace whitespace in filenames by underscore.""" import glob

如何替换给定父文件夹中文件夹、子文件夹和文件名称中的空格

下面给出了我最初尝试更换到8级的情况。我相信有更好的办法。我的代码看起来很难看。 更好的解决方案非常受欢迎

#!/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('*')

你需要一个递归的解决方案。重命名当前目录中的所有文件;然后,对于每个子目录(如果有),下降到该子目录X(使用
os.chdir(X)
),再次调用相同的函数,并上升回父目录(使用
os.chdir(“…”)
)。

您可以使用它动态更改迭代文件夹的名称:

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
(当前路径、文件列表、文件夹列表
)。给定的文件夹列表可以进行变异,
os.walk
将在迭代的以下步骤中使用变异的内容

运行前的文件夹:

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

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

按照@niemmi的确切想法,我最终得出以下结论:

警告:切勿从主目录或某些重要目录运行此脚本,它将重命名所有文件,包括隐藏文件

#!/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('.')

目标是什么?结果还是程序本身?您可以使用os.walk(),就像这里的答案:能够使用
os.rename
作为重命名文件的方法帮助了我,谢谢