shutil copy issue - python

So I have the following script
# Import system modules
import arcpy, os
import fnmatch
import shutil
import zipfile
zipf = zipfile.ZipFile('MXD_DC.zip', 'w', zipfile.ZIP_DEFLATED)
for root, dirs, files in os.walk(r"Y:\Data\MXD_DC"):
for file in files:
zipf.write(os.path.join(root, file))
shutil.copy(r'MXD_DC.zip', 'D:/')
After copying the file over to d drive when I try to unzip it, the error is "Before you can extract files, you must copy files to this compressed zipped folder". I can take the original zip file from the other drive and unzip it just fine. I can manually copy it over to d drive and unzip it just fine. It happens only when I use shutil to copy to the d drive.

You need to close the zipfile before you go to copy it. Either zipf.close() before the shutil.copy or
with zipfile.ZipFile('MXD_DC.zip', 'w', zipfile.ZIP_DEFLATED) as zipf:
for root, dirs, files in os.walk(r"Y:\Data\MXD_DC"):
for file in files:
zipf.write(os.path.join(root, file))
shutil.copy2('MXD_DC.zip','D:/')
You could also use shutil.copy2 again.

Related

how to cretae zip file using zipfile in python?

import os
from zipfile import ZipFile
from os.path import basename
src = "C:\git\mytest"
full_path=[]
for root, dirs, files in os.walk(src, topdown=False):
for name in files:
full_path.append(os.path.join(root, name))
with ZipFile('output.zip', 'w') as zipObj:
for item in full_path:
zipObj.write(item, basename(item))
Trying to create a zip file with containing some file of a specific folder.
In specific folder has some files. then it will add to zip file
In the mentioned code, one zipfile is created but there is no file. I am not getting the exact reason

Why I got infinity loop to add files in archive?

I started learn python and trying to create 'backup' app. Want to add files from chosen directory in zip archive, but I don't understand why zipfile.write adding the same files from directory in arhive non-stop? Also it add itself to archive.
import zipfile, os, pathlib, time
from os.path import basename
now = time.strftime('%H%M%S')
source3 = 'F:\oneMoreTry'
# create a ZipFile object
with zipfile.ZipFile(now + '.zip', 'w') as zipObj:
# Iterate over all the files in directory
for folderName, subfolders, filenames in os.walk(source3):
for filename in filenames:
# create complete filepath of file in directory
filePath = os.path.join(folderName, filename)
# Add file to zip
zipObj.write(filePath, basename(filePath))

Python - os.walk won't copy files from multiple folders

I have this script that hopefully moves all the files in multiple folders into a new folder. I used the os.walk and shtil.copy functions. However the script does not work.
Here is the script:
import os
import shutil
for root, dirs, filename in os.walk(r"C:\Users\edward\OneDrive\Suspensia Pictures"):
MoveFrom = r"C:\Users\edward\OneDrive\Suspensia Pictures"
MoveTo = r"C:\Users\edward\OneDrive\Pics"
shutil.copy(os.path.join(MoveFrom, filename), os.path.join(MoveTo, filename))
Here is the error I get:
TypeError: join() argument must be str, bytes, or os.PathLike object, not 'list'
import os
import shutil
from pathlib import Path
for path, subdirs, files in os.walk(r"C:\Users\edward\OneDrive\Suspensia Pictures"):
MoveFrom = r"C:\Users\edward\OneDrive\Suspensia Pictures"
MoveTo = r"C:\Users\edward\OneDrive\Pics"
for name in files:
shutil.copy(os.path.join(path, name), Path(MoveTo))
As the os.walk documentation said,
filenames is a list of the names of the non-directory files in dirpath.
which means that the filename in your code is type of list and that is not acceptable type for join().
Here's a possible way to solve it,
import os
import shutil
files: list
for root, dirs, files in os.walk(r"."):
source_path = r"."
target_path = r"../test"
for file in files:
if os.path.isfile(os.path.join(source_path)):
shutil.copy(os.path.join(source_path, file), os.path.join(target_path, file))
One thing that you should consider is that the files from the result of os.walk would be the files in each folder under the root, which is recursive. So, this script only is able to handle the files in the depth 1.
For moving all the files in each of the folder under your specific directory, this script may work.
import os
import shutil
files: list
for root, dirs, files in os.walk(r"."):
target_path = r"../test"
for file in files:
source_path = os.path.join(root, file)
shutil.copy(source_path, os.path.join(target_path, file))

How to copy the entire file into a zip file

I want to put a file in every file of .txt, .mp3, and mp4 files.
import zipfile
import os
path = "G:"
file_zip = zipfile.ZipFile(path+'\\archive.zip', 'w')
for folder, subfolders, files in os.walk(path):
for file in files:
if file.endswith('.jpg,.txt,.mp3,.mp4'):
file_zip.write(os.path.join(folder, file), os.path.relpath(os.path.join(folder,file), path), compress_type = zipfile.ZIP_DEFLATED)
file_zip.close()
When I open the zip file, the zip file is empty!
Try changing:
if file.endswith('.jpg,.txt,.mp3,.mp4'):
to:
if file.endswith(('.jpg', '.txt', '.mp3', '.mp4')):

How to compress a file with shutil.make_archive in python?

I want to compress one text file using shutil.make_archive command. I am using the following command:
shutil.make_archive('gzipped'+fname, 'gztar', os.path.join(os.getcwd(), fname))
OSError: [Errno 20] Not a directory: '/home/user/file.txt'
I tried several variants but it keeps trying to compress the whole folders. How to do it correctly?
Actually shutil.make_archive can make one-file archive! Just pass path to target directory as root_dir and target filename as base_dir.
Try this:
import shutil
file_to_zip = 'test.txt' # file to zip
target_path = 'C:\\test_yard\\' # dir, where file is
try:
shutil.make_archive(target_path + 'archive', 'zip', target_path, file_to_zip)
except OSError:
pass
shutil can't create an archive from one file. You can use tarfile, instead:
tar = tarfile.open(fname + ".tar.gz", 'w:qz')
os.chdir('/home/user')
tar.add("file.txt")
tar.close()
or
tar = tarfile.open(fname + ".tar.gz", 'w:qz')
tar.addfile(tarfile.TarInfo("/home/user/file.txt"), "/home/user/file.txt")
tar.close()
Try this and Check shutil
copy your file to a directory.
cd directory
shutil.make_archive('gzipped', 'gztar', os.getcwd())
#CommonSense had a good answer, but the file will always be created zipped inside its parent directories. If you need to create a zipfile without the extra directories, just use the zipfile module directly
import os, zipfile
inpath = "test.txt"
outpath = "test.zip"
with zipfile.ZipFile(outpath, "w", compression=zipfile.ZIP_DEFLATED) as zf:
zf.write(inpath, os.path.basename(inpath))
If you don't mind doing a file copy op:
def single_file_to_archive(full_path, archive_name_no_ext):
tmp_dir = tempfile.mkdtemp()
shutil.copy2(full_path, tmp_dir)
shutil.make_archive(archive_name_no_ext, "zip", tmp_dir, '.')
shutil.rmtree(tmp_dir)
Archiving a directory to another destination was a pickle for me but shutil.make_archive not zipping to correct destination helped a lot.
from shutil import make_archive
make_archive(
base_name=path_to_directory_to_archive},
format="gztar",
root_dir=destination_path,
base_dir=destination_path)

Categories

Resources