【问题标题】:How to copy zipfile from one folder to another folder using Python如何使用 Python 将 zipfile 从一个文件夹复制到另一个文件夹
【发布时间】:2020-05-03 11:52:54
【问题描述】:

请不要将问题标记为重复。我尝试了多个问题,但对我没有用。因此我提出了一个新问题。

问题:

我正在尝试将 zip 文件列表从源文件夹复制到目标文件夹。我尝试使用 shutil.copy 和 shutil.copyfile,但没有看到文件被复制到目标文件夹中。如果我做错了什么或有其他处理 zip 文件的方法,有人可以帮助我吗?以下是我的脚本,执行脚本时我没有看到任何错误。我在 Linux 机器上运行。

import os,shutil,time
source="/var/lib/jenkins/workspace/JobA/build-output"
destination="/var/lib/jenkins/workspace/JobA/m_output"
mod_files = ["file_1.zip","file_2.zip","file_3.zip","Folder_A","Folder_B"]
os.chdir(source)
if len(mod_files) != 0:
    for file in mod_files:
        if file in os.listdir(source) and file.endswith(".zip"):
            try:
                shutil.copy(file, destination)
                time.sleep(10)
                print("Copied ---- {} ---- to ---- {} ---- \n\n".format(file,
                                                                        destination))
            except Exception as e:
                print("Exception occurred while copying the file to destination \n {}".format(e))
        else:
            raise Exception("{} bundle doesn\'t exist in {} ".format(file, source))
else:
    sys.exit(0)

尝试过的问题

  1. How do I copy an entire directory of files into an existing directory using Python?
  2. How do I copy a file in Python?
  3. How to copy a file to a specific folder in a Python script?

【问题讨论】:

  • 如果您尝试过其他问题/答案,请将它们包含在您的问题中,以免您的问题被标记为重复。
  • 好的。我会用我尝试过的任何方法更新问题
  • 尝试 os.system('cp -r {} {}'.format(file, destination)) 而不是 shutil.copy 可能会有所帮助
  • 另外/var通常只能sudo,你有相应的写权限复制到/var吗?
  • 从最简单的复制文件的代码开始。确保它有效。编写一个循环来迭代所有文件。确保它有效。结合。利润。

标签: python


【解决方案1】:

问题在于您为函数 shutil.copy 提供的 source 参数,因此将 shutil.copy(file, destination) 更改为 shutil.copy(os.path.join(source, file), destination)

试试下面的代码,

import os,shutil
import time
source = "/var/lib/jenkins/workspace/JobA/build-output"
destination = "/var/lib/jenkins/workspace/JobA/m_output"
mod_files = ["file_1.zip","file_2.zip","file_3.zip","Folder_A","Folder_B"]
if len(mod_files) != 0:
    for file in mod_files:
        if file in os.listdir(source) and file.endswith(".zip"):
            try:
                shutil.copy(os.path.join(source, file), destination)
                time.sleep(10)
                print("Copied ---- {} ---- to ---- {} ---- \n\n".format(file,
                                                                        destination))
            except Exception as e:
                print("Exception occurred while copying the file to destination \n {}".format(e))
        else:
            raise Exception("{} bundle doesn\'t exist in {} ".format(file, source))
else:
    sys.exit(0)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-02
    • 1970-01-01
    • 2023-01-14
    • 2011-08-22
    相关资源
    最近更新 更多