Python剪切/复制粘贴文件从文件夹到另一个文件夹

时间:2020-08-18 14:19:29

标签: python directory directory-structure file-structure

我有一堆PDF,这些报告是由名为00002755、0002758、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都将进入各自的文件夹中。

1 个答案:

答案 0 :(得分: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}")