【问题标题】:Copy all JPG file in a directory to another directory in Python?将目录中的所有JPG文件复制到Python中的另一个目录?
【发布时间】:2012-08-10 13:47:44
【问题描述】:

我想将一个目录中的所有 JPG 文件复制到一个新目录。 我如何在 Python 中解决这个问题?我刚开始学习 Python。

感谢您的回复。

【问题讨论】:

标签: python


【解决方案1】:

当然,Python 提供了您需要的所有工具。要复制文件,您可以使用shutil.copy()。要查找源目录下的所有JPEG文件,可以使用glob.iglob()

import glob
import shutil
import os

src_dir = "your/source/dir"
dst_dir = "your/destination/dir"
for jpgfile in glob.iglob(os.path.join(src_dir, "*.jpg")):
    shutil.copy(jpgfile, dst_dir)

请注意,这将覆盖目标目录中名称匹配的所有文件。

【讨论】:

  • 非常感谢。它可以成功。但它似乎不适用于子目录中的JPG文件。如果我想获取所有JPG(包括子目录)如何制作?
  • @Seventeenager:您需要使用os.walk() 来遍历整个目录树——请参阅文档中的示例。
【解决方案2】:
import shutil 
import os 

for file in os.listdir(path):
    if file.endswith(".jpg"):
       src_dir = "your/source/dir"
       dst_dir = "your/dest/dir"
       shutil.move(src_dir,dst_dir)

【讨论】:

  • os.listdir(path) -- 这里 path 没有定义
【解决方案3】:
for jpgfile in glob.iglob(os.path.join(src_dir, "*", "*.jpg")):
    shutil.copy(jpgfile, dst_dir) 

您应该在“.jpg”之前写上“**”来搜索子目录。 more "" 表示要搜索的子目录更多

【讨论】:

    【解决方案4】:

    只需使用以下代码

    import shutil, os
    files = ['file1.txt', 'file2.txt', 'file3.txt']
    for f in files:
        shutil.copy(f, 'dest_folder')
    

    注意:您在当前目录中。 如果您有不同的目录,则在文件列表中添加路径。 即:

    files = ['/home/bucket/file1.txt', '/etc/bucket/file2.txt', '/var/bucket/file3.txt']
    

    【讨论】:

    • 未按要求定义源位置
    • @Displayname 当前目录为源文件。
    猜你喜欢
    • 1970-01-01
    • 2020-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-28
    相关资源
    最近更新 更多