0

我有一堆由名为 00002755、00002758、00002760 ... 等等的系统生成的报告。

我已经将文件夹命名为 00002755、00002758、00002760 ... 等等。

我想要实现的是剪切PDF文件“00002755.pdf”并将其粘贴到名为“00002755”的文件夹中

我的文件夹现在看起来像这样:

  1. 文件夹 - 00002755
  2. 文件夹 - 00002758
  3. 文件夹 - 00002760
  4. 00002755.pdf
  5. 00002758.pdf
  6. 00002760.pdf

结论是当我运行 python 脚本时,所有的 pdf 文件都会进入它们各自的文件夹。

4

1 回答 1

0

它可以用不同的模块以不同的方式完成,在这里我将只使用 os 应该很好而且也很快(永远不要用大量文件/目录对它进行基准测试,如果你需要它来完成你的任务,请随意这样做)

import os


curr_dir = os.path.dirname(os.path.realpath(__file__))  # Get current abspath based on your py file name

for i in [f.name for f in os.scandir(curr_dir) if f.is_dir()]:  # Iterate through the dirs
    for j in [f.name for f in os.scandir(curr_dir) if f.is_file()]:  # Iterate through the files
        if i == j.split(".pdf")[0]:  # If both match each other, move the file with os.rename
            os.rename(f"{curr_dir}\\{j}", f"{curr_dir}\\{i}\\{j}")
于 2020-08-18T15:01:58.077 回答