how to cretae zip file using zipfile in python? - 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

Related

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 open all files in a folder in Python? [duplicate]

This question already has answers here:
How do I list all files of a directory?
(21 answers)
Closed 1 year ago.
How do I open all files in a folder in python? I need to open all files in a folder, so I can index the files for language processing.
Here you have an example. here is what it does:
os.listdir('yourBasebasePath') returns a list of files in your directory
with open(os.path.join(os.getcwd(), filename), 'r') is opening the current file as readonly (you will not be able to write inside)
import os
for filename in os.listdir('yourBasebasePath'):
with open(os.path.join(os.getcwd(), filename), 'r') as f:
# do your stuff
How to open every file in a folder
I would recommend looking at the pathlib library https://docs.python.org/3/library/pathlib.html
you could do something like:
from pathlib import Path
folder = Path('<folder to index>')
# get all the files in the folder
files = folder.glob('**/*.csv') # assuming the files are csv
for file in files:
with open(file, 'r') as f:
print(f.readlines())
you can use os.walk for listing all the files having in your folder.
you can refer os.walk documentation
import os
folderpath = r'folderpath'
for root, dirs, files in os.walk(folderpath, topdown=False):
for name in files:
print(os.path.join(root, name))
for name in dirs:
print(os.path.join(root, name))
You can use
import os
os.walk()

How can I delete files by extension in subfolders of a folder?

I have a folder, which contains many subfolders, each containing some videos and .srt files. I want to loop over the main folder so that all the .srt files from all subfolders are deleted.
Here is something I tried-
import sys
import os
import glob
main_dir = '/Users/Movies/Test'
folders = os.listdir(main_dir)
for (dirname, dirs, files) in os.walk(main_dir):
for file in files:
if file.endswith('.srt'):
os.remove(file)
However, I get an error as follows-
FileNotFoundError: [Errno 2] No such file or directory: 'file1.srt'
Is there any way I can solve this? I am still a beginner so sorry I may have overlooked something obvious.
You need to join the filename with the location.
import sys
import os
import glob
main_dir = '/Users/Movies/Test'
folders = os.listdir(main_dir)
for (dirname, dirs, files) in os.walk(main_dir):
for file in files:
if file.endswith('.srt'):
source_file = os.path.join(dirname, file)
os.remove(source_file)

shutil copy issue

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.

Categories

Resources