PYTHON - Zip each file in directory independently - python

I've been looking through and have tried a few different codes without results. What I'm trying to do is zip each file in a subdirectory/folder independently.
Ex:
FileName.prj
FileName.dwg
FileName.mp3
Each as it's own .zip
Thanks!

Try this
import os
import zipfile
folder = "/tmp/in"
dest_folder = "/tmp/out"
l = [os.path.join(folder, fname) for fname in os.listdir(folder)]
os.chdir(folder)
for f in l:
f_name = f[f.rfind("/")+1:]+".zip"
z = zipfile.ZipFile(f_name, 'w')
z.write(f_name[:f_name.rfind(".zip")])
os.rename(folder+"/"+f_name, dest_folder+"/"+f_name)
where folder is you folder that contains files you want to zip and dest_folder is folder where the zip files will be written.

Related

delete all files from a path and keep only .parquet files using python

I have a path mydir where i have file1,file2, .. file100 each folder have .crc,.bak etc, files i want to remove all files and keep only .parquet files and name the .parquet files with folder name
for eg., file1 folder have .crc,.bak files after removing we end up with .parquet i need to name this as file1.parquet.
I tried to remove one folder but couldnot do it for all folders uisng python
can someone help me how to solve this
mydir='c/users/name/files'
for f in os.listdir(mydir):
if f.endswith(".parquet"):
continue
os.remove(os.path.join(mydir, f))
Following Miguel's comment, you can use glob like this:
import glob
import os
mydir = "./"
dir_to_remove = []
for src_file in glob.glob(mydir + '**/.parquet', recursive=True):
dir_, file_ = src_file.rsplit('/', 1)
dir_to_remove.append(dir_)
dst_file = dir_ + file_
os.rename(src_file, dst_file)
for dir_ in dir_to_remove:
os.rmdir(dir_)

How to open and load a JSON file inside a .zip archive?

So I have a python script I run in a directory which contains .zip files and these zip files all have JSON files which I want to load. With my current method I get an error of 'No such file or directory' when I try to 'open(filename)' I assume this is because namelist() doesn't actually enter the .zip directory. How can I load the JSON file inside this zip archive once I confirm that it is indeed a .zip archive?
import zipfile
import json
import os
myList = []
files = [f for f in os.listdir('.') if os.path.isfile(f)]
for f in files:
if f.endswith('.zip'):
with zipfile.ZipFile(f) as myzip:
for filename in myzip.namelist():
if filename.endswith('.json'):
g = open(filename)
data = json.load(g)
#do stuff with g and myList

Rename all files with different extensions to .txt in Python

I am trying to rename all files in a folder based on the extension. I want all files to be in .txt format. Files in the folder can be of different extension but I am trying to have them all renamed to .txt.
I tried to do the below
allFiles = 'Path where the files are located'
for filename in glob.iglob(os.path.join(allFiles, '*.0000')):
os.rename(filename, filename[:-5] + '.txt')
The above throws an error:
TypeError: expected str, bytes or os.PathLike object, not list
import os
def renameFilesToTxt(input_dir):
for path, subdirs, files in os.walk(input_dir):
for name in files:
filePath = os.path.join(path, name)
target_filePath = ''.join(filePath.split('.')[:-1])+".txt"
os.rename(filePath, target_filePath)
I create a script that will change your folder's all file extensions and the script is tested in my local pc.
In your desire folder run this script
import os
from pathlib import Path
items = os.listdir(".")
newlist = []
for names in items:
if names.endswith(".0000"):
newlist.append(names)
for i in newlist:
print(i)
p = Path(i)
p.rename(p.with_suffix('.txt'))
[Note : THE SCRIPT IS TESTED AND ITS WORK]

proper way for zipping files in python

I'm trying to create a zip file by zipping couple text files from a specific directory. My code looks like the following:
import zipfile,os
project='C:/Users/user1/Documents/work/filesToZip'
dirlist = os.listdir(project)
print dirlist
zip_name = zipfile.ZipFile(os.path.join(project,'jobs.zip'),'w')
for file in dirlist:
zip_name.write(os.path.join(project,file))
zip_name.close()
the code runs fine and it creates the zip file, the only problem is when I open the zip file I found the whole directory structure is zipped. i.e. when I open the file I will find Users open it then user1 open it then Documents open it then work then filesToZip then I find the files I want to zip. my question is how can I get red of the file structure so when I open the zip file I find the files I zipped right away?
Thanks in advance!
ZipFile.write has an optional second parameter archname
which does exactly what you want.
import zipfile,os
project='C:/Users/user1/Documents/work/filesToZip'
# prevent adding zip to itself if the old zip is left in the directory
zip_path = os.path.join(project,'jobs.zip')
if os.path.exists(zip_path):
os.unlink(zip_path);
dirlist = os.listdir(project)
zip_file = zipfile.ZipFile(zip_path, 'w')
for file_name in dirlist:
zip_file.write(os.path.join(project, file_name), file_name)
zip_file.close()
For python 2.7+ you can use shutil instead:
from shutil import make_archive
make_archive(
'zipfile_name',
'zip', # the archive format - or tar, bztar, gztar
root_dir=None, # root for archive - current working dir if None
base_dir=None) # start archiving from here - cwd if None too
This way you can explicitly specify which directory should be the root_dir and which should be the base_dir. If root_dir and base_dir are not the same, it will only zip the files in base_dir but preserve the directory structure up to root_dir
import zipfile,os
project='C:/Users/user1/Documents/work/filesToZip'
original_dir= os.getcwd()
os.chdir(project)
dirlist = os.listdir(".")
print dirlist
zip_name = zipfile.ZipFile('./jobs.zip','w')
for file in dirlist:
zip_name.write('./'+file)
zip_name.close()
os.chdir(original_dir)

Extract files from a zip folder with sub folders into a single folder

I have a zip folder with several subfolders.
testfolder.zip contains files in the given format
testfolder/files 1,2,3
testfolder/Test1folder/files 5,6
testfolder/Test2folder/files 7,8
I need the output as
testfolder/files 1,2,3,4,5,6,7,8
I am able to unzip the folder with its subfolders but not in the desired way.
This is my attempt so far
import glob
import os
import zipfile
folder = 'E:/Test'
extension = '.zip'
zip_files = glob.glob(folder + extension)
for zip_filename in zip_files:
dir_name = os.path.splitext(zip_filename)[0]
os.mkdir(dir_name)
zip_handler = zipfile.ZipFile(zip_filename, "r")
zip_handler.extractall(dir_name)
Any help will be very appreciated.Thanks in advance.
Replace:
zip_handler.extractall(dir_name)
with something like this:
for z in zip_handler.infolist():
zip_handler.extract(z, dir_name)
This should by taking each file in the archive at a time and extracting it to the same point in the directory.
UPDATE:
Apparently it still extracts them relatively. Solved it by adding a few lines of code to your original snippet:
for p, d, f in os.walk(folder, topdown= False):
for n in f:
os.rename(os.path.join(p, n), os.path.join(dir_name, n))
for n in d:
os.rmdir(os.path.join(p, n))
This will move the files into the base folder and delete all empty folders that remain. This one I have tried and tested.

Categories

Resources