Zip a directory and save it in another destination - python-3.x

I have the following script for zip a directory:
zipobj = zipfile.ZipFile(zip_file_name + '.zip', 'w', zipfile.ZIP_DEFLATED)
rootlen = len(target_dir) + 1
for base, dirs, files in os.walk(target_dir):
for file in files:
fn = os.path.join(base, file)
zipobj.write(fn, fn[rootlen:])
Currently it works fine, but the new zip file is saved in my root path.
How do I save it in other destination?

Related

Does pysmb support copying .zip files

I am trying to copy .zip files from a shared network folder to a unix environment using pysmb. The process will copy the .zip file names, but not the contents of the files
smbFolder = "networkdrive"
conn = SMBConnection('username', 'password', smbFolder,'')
conn.connect(smbFolder)
Share='shareFolder'
ShareFolder='TargetFolder'
ShareFilename = ShareFolder
Contents = conn.listPath(Share, ShareFolder)
for Content in Contents:
try:
conn.retrieveFile(Content, open(savePath + '/' + Content.filename, 'wb'))
except: None
conn.close()
Expecting this to copy zip files to the savePath folder along with the contents of the zip file, but zip files are copied as empty folders

FileNotFoundError when using shutil.copy()

I want to copy the source file to the destination folder.
In the destination folder, I am creating n number of folders (That may be nested of any depth) and I want to paste file1.pdf in any random folders inside the destination folder.
I have done the following code
import shutil
destination_folder = "path_to_the_destination_folder"
source_file = "path_to_source_file\file1.pdf"
destination_file = "f{destination_folder}\any_random_folder_from_n_nested_folders\file1.pdf"
new_file= shutil.copy(source_file, destination_file )
print(new_file)
FYI: "destination_folder\any_random_folders_from_n_nested_folders" This path is present, means it is getting created successfully , checked using os.path.isdir()
And facing this issue for some files, not for all files..
But it is giving me an error:
FileNotFoundError: [Errno 2] No such file or directory:
File "\AppData\Local\Programs\Python\Python39\lib\shutil.py", line 420, in copy
copyfile(src, dst, follow_symlinks=follow_symlinks)
File "\AppData\Local\Programs\Python\Python39\lib\shutil.py", line 265, in copyfile
with open(src, 'rb') as fsrc, open(dst, 'wb') as fdst:
FileNotFoundError: [Errno 2] No such file or directory
I believe, you have incorrectly specified destination folder, try this:
import shutil
destination_folder = "path_to_the_destination_folder"
source_file = "path_to_source_file\file1.pdf"
destination = f"{destination_folder}\any_random_folders_from_n_nested_folders\file1.pdf"
dest = shutil.copy(source_file, destination)
print(dest)
If this doesn't work, then check if all the directories exist and also check the permissions.
This is issue is resolved..
I just changed folder names which I was creating according to user input.
Previous folder names: f"Fld+{datetimestamp}"
Current folder names: f"Fld+{folder_counter}"

How to resolve the path of a file name in python with symlink on linux

i am trying to resolve the path of a file that has been symlink in python on linux os
i have tried this
# sets up the log directory for all files
log_dir = os.path.join(os.path.normpath(os.getcwd() + os.sep + os.pardir),'logs')
try os.readlink. Assuming log_dir is your soft link,
soft_link = os.path.join(
os.path.normpath(os.getcwd() + os.sep + os.pardir),
'logs',
)
abs_path = os.readlink(soft_link)
os.readlink
Return a string representing the path to which the symbolic link points.

Python: how to move through folder recursively and shutil.move() files to target folders

Beginner here. I want to be able to traverse folders and their subdirectorys and files and move all unique file extensions into a dedicated folder for that filetype. Ex .jpg -> into jpg folder. (This is all in Python's IDLE)
I have this code:
os.chdir('c:\\users\\dchrie504\\Downloads_2')
# walk through all files and folders to get unique filetypes.
l_Files = os.walk('c:\\users\\dchrie504\\Downloads_2')
fileTypes = []
for walk in l_Files:
for file in walk[-1]:
fileTypes.append(file.split('.')[-1])
# make all items lowercase to create distinct values
fileTypes = [x.lower() for x in fileTypes]
# get rid of duplicate filetypes by creating set then back to list.
fileTypes = set(fileTypes)
fileTypes = list(fileTypes)
# create a folder for each unique filetype.
for ft in fileTypes:
os.mkdir(os.getcwd() + '\\' + ft)
fileWalk = os.walk('c:\\users\\dchrie504\\Downloads_2')
#Trying to move files to their respective fileType folder.
for fileType in fileTypes:
for folder, sub, files in os.walk('c:\\users\\dchrie504\\Downloads_2'):
for file in files:
if file.endswith('.' + fileType):
shutil.move(file, (os.getcwd() + '\\' + fileType))
Problem is I get the following error when this part executes:
for file in files:
if file.endswith('.' + fileType):
shutil.move(file, (os.getcwd() + '\\' + fileType))
Error Message: Traceback (most recent call last):
File "", line 5, in
shutil.move(file, (os.getcwd() + '\' + fileType))
File "C:\Users\dchrie504\AppData\Local\Programs\Python\Python37-32\lib\shutil.py", line 555, in move
raise Error("Destination path '%s' already exists" % real_dst)
shutil.Error: Destination path 'c:\users\dchrie504\Downloads_2\txt\New Text Document.txt' already exists
you have to give the full path so shutil.move will overwrite.
shutil.move(fullpathorigin, fullpathdestination)

How to create a folder and write N files into folder in Python in Windows & again read those N files into Python

Here I am trying to take dirname from file_path and add new_folder then write the files into the folder.
dirctry = os.path.dirname(file_path)
toolSharePath = os.path.abspath(dirctry)
final_directory = os.path.join(toolSharePath, r'new_folder')
if not os.path.exists(final_directory):
os.makedirs(final_directory,exist_ok=True)
with open(final_directory, "w") as f:
f.write("data")

Resources