简体   繁体   English

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

[英]Rename files in subfolders with python and os.walk()

I want to rename all the files in subfolders of two parent directories replacing spaces with underscores.我想重命名两个父目录的子文件夹中的所有文件,用下划线替换空格。 This is my structure:这是我的结构:

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

This is the result I want:这是我想要的结果:

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

This is the script that I'm using and which so far is not doing anything:这是我正在使用的脚本,到目前为止还没有做任何事情:

#!/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

What am I overlooking?我在看什么?

You are probably running in the issue where you have renamed a folder, before the os.walk has finished walking through it.os.walk完成遍历之前,您可能遇到了重命名文件夹的问题。 This can be solved by setting topdown=False .这可以通过设置topdown=False来解决。 Now you will first receive the lowest files, and folders.现在您将首先收到最低的文件和文件夹。

Then you can update the files first and then the folders.然后您可以先更新文件,然后再更新文件夹。

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)

Edit编辑

The following structure and code was used to test the script:以下结构和代码用于测试脚本:

  • Folder structure文件夹结构
└───parent
    ├───folder 1
    │   └───TIFF
    │         ├─── file 1.txt
    │         └─── file 2.txt
    ├───folder 2
    │    └───TIFF
    │         ├─── file 1.txt
    │         └─── file 2.txt
    └─── main.py
  • Code 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'))

Doing os.chdir() inside os.walk() is almost certainly wrong.os.walk()中执行os.chdir()几乎可以肯定是错误的。

Also, take care to not rename parent directories whilst you are traversing their children.此外,请注意不要在遍历其子目录时重命名父目录。

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

Your code never calls replace() so perhaps that's the first thing you are missing, though.您的代码从不调用replace()所以也许这是您缺少的第一件事。 Declaring a function just tells Python what to do if and when you call that function later on.声明 function 只是告诉 Python 如果以及当您稍后调用 function 时该怎么办。

If you don't need to recurse really, just do如果您真的不需要递归,只需执行

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)

when you using os.chdir method,because your working directory is always changing,you should use os.getcwd to see the current working directory,you will know what's wrong,and then change the working directory to parent first,then you can change it as you wish.当你使用os.chdir方法时,因为你的工作目录一直在变化,你应该使用os.getcwd查看当前工作目录,你就会知道哪里出了问题,然后先将工作目录更改为父目录,然后你可以更改它如你所愿。

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

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