Zipping Directory or file(s) in python - python-2.7

I'm trying to zip files present in a directory and give a specific name (destination folder) to it. I want to pass the source and destination folders as input to the program.
But when ever I'm passeing the source file path it's giving me and error. I guess I'll face the same problem with the destination file path.
d:\SARFARAZ\Python>python zip.py
Enter source directry:D:\Sarfaraz\Python\Project_Euler
Traceback (most recent call last):
File "zip.py", line 17, in <module>
SrcPath = input("Enter source directry:")
File "<string>", line 1
D:\Sarfaraz\Python\Project_Euler
^
SyntaxError: invalid syntax
The code I've written is as follow:
import os
import zipfile
def zip(src, dst):
zf = zipfile.ZipFile("%s.zip" % (dst), "w", zipfile.ZIP_DEFLATED)
abs_src = os.path.abspath(src)
for dirname, subdirs, files in os.walk(src):
for filename in files:
absname = os.path.abspath(os.path.join(dirname, filename))
arcname = absname[len(abs_src) + 1:]
print 'zipping %s as %s' % (os.path.join(dirname, filename),arcname)
zf.write(absname, arcname)
zf.close()
#zip("D:\\Sarfaraz\\Python\\Project_Euler", "C:\\Users\\md_sarfaraz\\Desktop")
SrcPath = input("Enter source directry:")
SrcPath = ("#'"+ str(SrcPath) +"'")
print SrcPath # checking source path
DestPath = input("Enter destination directry:")
DestPath = ("#'"+str(DestPath) +"'")
print DestPath
zip(SrcPath, DestPath)

i have made some changes to your code as follows:
import os
import zipfile
def zip(src, dst):
zf = zipfile.ZipFile(dst, "w", zipfile.ZIP_DEFLATED)
abs_src = os.path.abspath(src)
for dirname, subdirs, files in os.walk(src):
for filename in files:
absname = os.path.abspath(os.path.join(dirname, filename))
arcname = absname[len(abs_src) + 1:]
print 'zipping %s as %s' % (os.path.join(dirname, filename),arcname)
zf.write(absname, arcname)
zf.close()
# Changed from input() to raw_input()
SrcPath = raw_input("Enter source directory: ")
print SrcPath # checking source path
# done the same and also added the option of specifying the name of Zipped file.
DestZipFileName = raw_input("Enter destination Zip File Name: ") + ".zip" # i.e. test.zip
DestPathName = raw_input("Enter destination directory: ")
# Here added "\\" to make sure the zipped file will be placed in the specified directory.
# i.e. C:\\Users\\md_sarfaraz\\Desktop\\
# i.e. double \\ to escape the backlash character.
DestPath = DestPathName + "\\" + DestZipFileName
print DestPath # Checking Destination Zip File name & Path
zip(SrcPath, DestPath)
Good Luck!

Related

How to ignore exception and continue loop in python?

I have a python function that adds the directory to zip file in TEMP directory, but when I launch it I get an exception -> IOError: [Errno 13] Permission denied: 'NTUSER.DAT'. Of course, I will not have access to this file and after exception loop breaks and application exit, so I wanted to know how to make loop continue even after exception?
import zipfile
import sys
import os
_DIR_TO_ZIP = os.environ['USERPROFILE']
_ZIPPED_FILE = os.environ['TEMP'] +"\\" +os.environ['USERNAME'] +".zip"
def zip_folder(folder_path, output_path):
"""Zip the contents of an entire folder (with that folder included
in the archive). Empty subfolders will be included in the archive
as well."""
parent_folder = os.path.dirname(folder_path)
# Retrieve the paths of the folder contents.
contents = os.walk(folder_path)
try:
zip_file = zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED)
for root, folders, files in contents:
# Include all subfolders, including empty ones.
for folder_name in folders:
absolute_path = os.path.join(root, folder_name)
relative_path = absolute_path.replace(parent_folder + '\\',
'')
print "Adding '%s' to archive." % absolute_path
zip_file.write(absolute_path, relative_path)
for file_name in files:
absolute_path = os.path.join(root, file_name)
relative_path = absolute_path.replace(parent_folder + '\\',
'')
print "Adding '%s' to archive." % absolute_path
zip_file.write(absolute_path, relative_path)
print "'%s' created successfully." % output_path
zip_file.close()
except:
pass
if __name__ == '__main__':
zip_folder(_DIR_TO_ZIP, _ZIPPED_FILE)
If you want to keep your current function:
Use the tempfile module, it's cleaner and handles the temp paths
Simply insert try/except statements at a lower level, where you expect some elements of the yielded objects to fail.

I am trying to rename a bunch of files in a directory but I am getting an error("NameError: name 'root' is not defined") when saving renamed files

htnl_files is my directory and I have to remove "https:##www.wisdomjobs.com#e-university#" part from the every file of my directory and I need to save files to same directory.
import os
file_names=os.listdir('html_files')
for file_name in file_names:
#print file_name
file_name = file_name.replace("https:##www.wisdomjobs.com#e-university#","")
#print filename
fullpath = os.path.join(root/html_files, file_name)
os.rename(fullpath, file_name)
neither root nor html_files are defined in your code. what you probably want is this:
import os
file_names = os.listdir('html_files')
for orig_name in file_names:
new_name = orig_name.replace("https:##www.wisdomjobs.com#e-university#", "")
orig_path = os.path.join('html_files', orig_name)
new_path = os.path.join('html_files', new_name)
os.rename(orig_path, new_path)

Unzip csv file from Zip on ftp server

I want to log into a ftp server (not a public url) and download a csv file which is located in a zip file and then save this to a particular directory:
#log in OK
# this is the zip file I want to download
fpath = strDate + ".zip"
#set where to save file
ExtDir = "A:\\LOCAL\\DIREC\\TORY\\"""
ExtDir = ExtDir + strdate + "\\"
ExtFile = ExtDir + "Download.zip"
#download files
#use zipfile.ZipFile as alternative method to open(ExtFile, 'w')
with zipfile.ZipFile(ExtFile,'w') as outzip:
ftp.retrbinary('RETR %s' % fpath , outzip.write)
outzip.close
I get this error
File "C:\Program Files (x86)\Python 2.7\lib\ftplib.py", line 419, in retrbinary callback(data)
File "C:\Program Files (x86)\Python 2.7\lib\zipfile.py", line 1123, in write st = os.stat(filename)
TypeError: stat() argument 1 must be encoded string without null bytes, not str
Fixed using:
ftp.retrlines('RETR %s' % fpath ,lambda s, w=outzip.write: w(s+"\n"))

downloading multiple files with urllib.urlretrieve

I'm trying to download multiple files from a website.
The url resembles this: foo.com/foo-1.pdf.
Since I want those files to be stored in a directory of my choice,
I have written the following code:
import os
from urllib import urlretrieve
ext = ".pdf"
for i in range(1,37):
print "fetching file " + str(i)
url = "http://foo.com/Lec-" + str(i) + ext
myPath = "/dir/"
filename = "Lec-"+str(i)+ext
fullfilename = os.path.join(myPath, filename)
x = urlretrieve(url, fullfilename)
EDIT : Complete error message.
Traceback (most recent call last):
File "scraper.py", line 10, in <module>
x = urlretrieve(url, fullfilename)
File "/usr/lib/python2.7/urllib.py", line 94, in urlretrieve
return _urlopener.retrieve(url, filename, reporthook, data)
File "/usr/lib/python2.7/urllib.py", line 244, in retrieve
tfp = open(filename, 'wb')
IOError: [Errno 2] No such file or directory: /dir/Lec-1.pdf'
I'd be grateful if someone could point out where I have gone wrong.
Thanks in advance!
As for me your code works (Python3.9). So make sure your script has access to the directory you've specified. Also, it looks like you are trying to open a file which does not exist. So make sure you've downloaded the file before opening it:
fullfilename = os.path.abspath("d:/DownloadedFiles/Lec-1.pdf")
print(fullfilename)
if os.path.exists(fullfilename): # open file only if it exists
with open(fullfilename, 'rb') as file:
content = file.read() # read file's content
print(content[:150]) # print only the first 150 characters
The output would be as follows:
C:/Users/Administrator/PycharmProjects/Tests/dtest.py
d:\DownloadedFiles\Lec-1.pdf
b'%PDF-1.6\r%\xe2\xe3\xcf\xd3\r\n2346 0 obj <</Linearized 1/L 1916277/O 2349/E 70472/N 160/T 1869308/H [ 536 3620]>>\rendobj\r \r\nxref\r\n2346 12\r\n0000000016 00000 n\r'
Process finished with exit code 0

shutil.make_archive creates zip file , but skips empty directories

Im not sure what im doing wrong, but what i need is to create a zip file with all files and folders ( empty or not ) of a given directory. So, at the moment i have this simple code that "works" but it doens't add empty folders :|
content of c:\temp\trashtests
c:\temp\trashtests\a\a.txt
c:\temp\trashtests\b\b.txt
c:\temp\trashtests\c
c:\temp\trashtests\d
Current code:
class ZipTools:
"""
Zip tools
"""
def __init__(self, target_path=None, zip_name=None):
self.path = target_path
self.zip_name = zip_name
def create_zip(self):
shutil.make_archive(self.zip_name, format='zip', root_dir=self.path)
execution:
ab = self.ZipTools('c:\temp\trashtests', 'c:\test\a.zip')
ab.create_zip()
The output is a zip file only with:
\a\a.txt
\b\b.txt
So, how can i create a zip file with all contents of a given directory using shutils? If not, how could i do it using zipfile?
Thanks in advance.
EDIT:
As sugested by J.F. Sebastian, i tried the solution of this question but it didn't worked since it created a zip file with the following structure:
File: a.zip
Content:
c:
a\a.txt
b\b.txt
I'm still trying to figure it out a solution :)
I was able to solve this problem using using this code:
An important note, this code works for what i need, which is:
Zip an existing folder with the same name of the zip file to create.
import os
import sys
import zipfile
class ZipTools:
"""
Zip tools
"""
def __init__(self, folder_path=None, pkg_zip=None):
self.path = folder_path
self.zip_name = pkg_zip
self.temp_dir = 'c:\\temp'
self.archive = '{p}\\{z}'.format(p=self.temp_dir, z='a.zip')
def zip(self):
parent_folder = os.path.dirname(self.path)
# Retrieve the paths of the folder contents.
contents = os.walk(self.path)
try:
zip_file = zipfile.ZipFile(self.archive, 'w', zipfile.ZIP_DEFLATED)
for root, folders, files in contents:
# Include all subfolders, including empty ones.
for folder_name in folders:
ab_path = os.path.join(root, folder_name)
rel_path = ab_path.replace(parent_folder + '\\' + self.zip_name, '')
print rel_path
zip_file.write(ab_path, rel_path)
for file_name in files:
ab_path = os.path.join(root, file_name)
rel_path = ab_path.replace(parent_folder + '\\' + self.zip_name, '')
zip_file.write(ab_path, rel_path)
except zipfile.BadZipfile, message:
print message
sys.exit(1)
finally:
zip_file.close()
if __name__ == '__main__':
ab = ZipTools('c:\\temp\\trashtests', 'a.zip')
ab.zip()