简体   繁体   English

Python遍历文件夹并重命名文件

[英]Python loop through folders and rename files

I am trying to go through a bunch of folders and go into each one and rename specific files to different names. 我试图浏览一堆文件夹,进入每个文件夹,然后将特定文件重命名为不同的名称。 I got stuck on just the loop through folders part. 我被卡在文件夹循环中。

My file system looks as follows: 我的文件系统如下所示:

Root Directory
Folder
    File1
    File2
    File3
Folder
    File1
    File2
    File3

The code I have is: 我的代码是:

os.chdir(rootDir)

for folder in os.listdir():
    print(folder)
    os.chdir(rootDir + 'folder')
    for f in os.listdir():
        print(f)
    os.chdir(rootDir)

So in my mind it will go through the folders then enter the folder and list the files inside then go back to the root directory 因此在我看来,它将遍历文件夹,然后进入文件夹并列出其中的文件,然后返回到根目录

Have a look at os.walk 看看os.walk

import os
for dir, subdirs, files in os.walk("."):
    for f in files:
        f_new = f + 'bak'
        os.rename(os.path.join(root, f), os.path.join(root, f_new))

You need os.walk . 您需要os.walk It returns a 3-tuple (dirpath, dirnames, filenames) that you can iterate. 它返回一个3元组(目录路径,目录名,文件名),您可以对其进行迭代。

def change_files(root_dir,target_files,rename_fn):
    for fname in os.listdir(root_path):
        path = os.path.join(root_path,fname)
        if fname in target_files:
           new_name = rename_fn(fname)
           os.move(path,os.path.join(root_path,new_name)

def rename_file(old_name):
    return old_name.replace("txt","log")

change_files("/home/target/dir",["File1.txt","File2.txt"],rename_file)

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

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