Auto-learner
Auto-learner

Reputation: 1511

How to copy zipfile from one folder to another folder using Python

Please don't mark the question as a duplicate. I have tried multiple questions and it didn't work for me. hence I am raising a new question.

Problem :

I am trying to copy a list of zip files from my source to the destination folder.I have tried using shutil.copy and shutil.copyfile but I don't see the file getting copied into my destination folder. Can someone help me if I am doing anything wrong or is there any other way of handling zip files. Following is my script and I don't see any error while executing the script. I am running on a Linux machine.

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)

Questions tried

  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?

Upvotes: 4

Views: 6626

Answers (1)

Shibiraj
Shibiraj

Reputation: 769

The issue was with the argument you have give for source for the function shutil.copy, so change shutil.copy(file, destination) to shutil.copy(os.path.join(source, file), destination)

Try the code below,

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)

Upvotes: 1

Related Questions