在 Python 中将文件批量重命名为其目录结构的一部分

Batch rename of files to a part of their directory structure in Python

首先,我是 Python 和一般编程的新手。我希望重命名的文件位于这种格式中,其中 SampleID 是一个唯一 ID:

/home/MattXD/Documents/Processed/Untitled 文件夹/SampleID/subfolder/report.pdf

我想将所有 report.pdf 个文件重命名为 SampleID.pdf

import os, sys, shutil

topdir = '/home/MattXD/Documents/Processed/Untitled Folder/'
exten = 'report.pdf'

for dirpath, dirnames, files in os.walk(topdir):
    for name in files:
        if name.lower().endswith(exten):
            oldfile = os.path.join(dirpath, name)
            newname = oldfile.split('/')[6]
            print name
            print newname
            shutil.copy2(oldfile, '/home/MattXD/Documents/Processed/Untitled Folder/%s' % newname)

我觉得我接近正确的轨道,正如我从 print nameprint newname 中看到的那样,我在 oldfile 和新名称中存储了正确的文件我想在 newname 中使用。我似乎无法重命名该文件!

我想我误用了 shutil.copy2,我的 for 循环可能有问题,因为我得到一个错误,文件名(report.pdf 和 report.pdf)相同(它们是)。感谢阅读。

嗯,实际上有一个 os.rename 函数:

os.rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)

Rename the file or directory src to dst. If dst is a directory, OSError will be raised. On Unix, if dst exists and is a file, it will be replaced silently if the user has permission. The operation may fail on some Unix flavors if src and dst are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement). On Windows, if dst already exists, OSError will be raised even if it is a file.

This function can support specifying src_dir_fd and/or dst_dir_fd to supply paths relative to directory descriptors.

If you want cross-platform overwriting of the destination, use replace().

Availability: Unix, Windows.

如果您坚持使用shutilshutil.move是您的选择。