【问题标题】:Python Cut/Copy paste file from folder to another folderPython从文件夹剪切/复制粘贴文件到另一个文件夹
【发布时间】:2020-12-07 18:10:36
【问题描述】:

我有一堆 PDF 是由系统生成的报告,名为 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 文件都会进入它们各自的文件夹。

【问题讨论】:

  • 到底是什么问题?要在 python 中移动文件,您可以在循环中使用 shutil 模块和 os.listdir()
  • @SuperKeksmann,问题只是将“命名”PDF 剪切粘贴到“命名”文件夹中……python 操作系统模块按照 SCL 的回答工作。谢谢。

标签: python directory directory-structure file-structure


【解决方案1】:

它可以用不同的模块以不同的方式完成,这里我将只使用 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}")

【讨论】:

  • 谢谢伙计!这就像魅力一样。为我节省了很多时间在剪切粘贴到文件夹中的无意义任务以及如果将错误的文件复制到错误的文件夹中可能发生的错误。
猜你喜欢
  • 1970-01-01
  • 2023-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多