繁体   English   中英

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

[英]Rename files in subfolders with python and 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

我在看什么?

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'))

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

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

#!/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()所以也许这是您缺少的第一件事。 声明 function 只是告诉 Python 如果以及当您稍后调用 function 时该怎么办。

如果您真的不需要递归,只需执行

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)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM