【问题标题】:how to combine all the files of one directory of one extension into one folder如何将一个扩展名的一个目录的所有文件合并到一个文件夹中
【发布时间】:2020-09-23 02:01:58
【问题描述】:

如何将一个目录的所有 PDF 文件(此 pdf 可以位于不同目录的深度)合并到一个新文件夹中?

我已经试过了:

new_root = r'C:\Users\me\new_root'
root_with_files = r'C:\Users\me\all_of_my_pdf_files\'

for root, dirs, files in os.walk(root_with_files):
    for file in files:
        os.path.join(new_root, file)

但它不会向我的文件夹添加任何内容

【问题讨论】:

  • 我认为 join 不能那样工作。也许你应该试试this post的功能

标签: python operating-system


【解决方案1】:

你可以试试这个:

import shutil

new_root = r'C:\Users\me\new_root'
root_with_files = r'C:\Users\me\all_of_my_pdf_files'

for root, dirs, files in os.walk(root_with_files):
    for file in files:
        if file.lower().endswith('.pdf') :  # .pdf files only
            shutil.copy( os.path.join(root, file), new_root )

【讨论】:

  • 顺便说一句,如果我想要所有文件,我想我不需要lower()
  • 好的,lower 不只检查较低的文件,谢谢,这是正确的
  • @germanjke 对错字表示抱歉。现在修好了。感谢您发现它=)
【解决方案2】:

您的代码不会将任何文件移动到新文件夹。你可以使用os.replace(src,dst)移动你的文件。

试试这个:

new_root = r'C:\Users\me\new_root'
root_with_files = r'C:\Users\me\all_of_my_pdf_files\'

for root, dirs, files in os.walk(root_with_files):
    for file in files:
        os.replace(os.path.join(root, file),os.path.join(new_root, file))

【讨论】:

  • 但是我有一个 empy 新文件夹 new_root 所以我没有任何东西可以替换我可以添加文件吗?
  • 是的,你可以。 os.replace(src,dst) 将移动您的文件。如果dst存在,则会被替换,
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多