使用 python 和 os.walk() 重命名子文件夹中的文件

时间:2020-12-22 12:21:38

标签: python python-3.x rename os.walk

我想重命名两个父目录的子文件夹中的所有文件,用下划线替换空格。这是我的结构:

parent folder
    folder 1
        TIFF
             image 1
             image 2
             [...]
    folder 2
        TIFF
             image 1
             image 2
             [...]
    [...]

这是我想要的结果:

parent folder
    folder_1
        TIFF
             image_1
             image_2
             [...]
    folder_2
        TIFF
             image_1
             image_2
             [...]
    [...]

这是我正在使用的脚本,到目前为止还没有做任何事情:

#!/usr/local/bin/python3

import os

def replace(parent):
    for path, folders, files in os.walk(parent):

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

我忽略了什么?

3 个答案:

答案 0 :(得分:1)

您可能遇到了重命名文件夹的问题,os.walk 尚未完成遍历。这可以通过设置 topdown=False 来解决。现在您将首先收到最低的文件和文件夹。

然后您可以先更新文件,然后再更新文件夹。

import os


def rename(path, file):
    old_file = os.path.join(path, file)
    new_file = os.path.join(path, file.replace(' ', '_'))
    os.rename(old_file, new_file)


def replace(parent):
    for path, folders, files in os.walk(parent, topdown=False):
        print(path, folders, files)
        for file in files:
            rename(path, file)
        for folder in folders:
            rename(path, folder)

编辑

以下结构和代码用于测试脚本:

  • 文件夹结构
└───parent
    ├───folder 1
    │   └───TIFF
    │         ├─── file 1.txt
    │         └─── file 2.txt
    ├───folder 2
    │    └───TIFF
    │         ├─── file 1.txt
    │         └─── file 2.txt
    └─── main.py
  • 代码main.py

import os


def rename(path, file):
    old_file = os.path.join(path, file)
    new_file = os.path.join(path, file.replace(' ', '_'))
    os.rename(old_file, new_file)


def replace(parent):
    for path, folders, files in os.walk(parent, topdown=False):
        print(path, folders, files)
        for file in files:
            rename(path, file)
        for folder in folders:
            rename(path, folder)


if __name__ == '__main__':
    parent = os.path.dirname(__file__)
    replace(os.path.join(parent, 'parent'))

答案 1 :(得分:0)

os.chdir() 内执行 os.walk() 几乎肯定是错误的。

另外,注意不要在遍历子目录时重命名父目录。

#!/usr/local/bin/python3

import os

def replace(parent):
    remembrance = []
    for path, folders, files in os.walk(parent):
        if os.path.basename(path) == "TIFF":
            for f in files:
                os.rename(os.path.join(path, f), os.path.join(path, f.replace(' ', '_')))
        elif "TIFF" in folders:
            remembrance.append((path, os.path.join(os.path.dirname(path), os.path.basename(path).replace(" ", "_"))))
    for src, dst in remembrance:
        os.rename(src, dst)

您的代码从不调用 replace() 所以也许这是您遗漏的第一件事。声明一个函数只是告诉 Python 在稍后调用该函数时该做什么。

如果你真的不需要递归,就去做

import os
import glob

def underscorify(path):
    os.rename(path, os.path.join(os.path.dirname(path), os.path.basename(path).replace(" ", "_"))    

for file in glob.glob("*/TIFF/*"):
    underscorify(file)
for dirname in glob.glob("*/"):
    if os.path.exists(os.path.join(dirname), "TIFF"):
        underscorify(dirname)

答案 2 :(得分:0)

当你使用os.chdir方法时,因为你的工作目录一直在变化,你应该使用os.getcwd查看当前工作目录,你就会知道哪里出了问题,然后将工作目录更改为parent首先,然后您可以随意更改它。

相关问题