Python how to revert move operation into a file - python

I want to know if and how it's possible to revert a move operation or deconstruct the file that was created. I wrote a script that should've moved all nested jpg files into a folder but instead wrote it to a file. This is due to an error in the target path, I missed the slash at the end to denote it was folder.
This is the code that created the mistake:
#!/usr/bin/python3
from sys import argv
from os import walk, path
from fnmatch import fnmatch
from shutil import move
rootdir = argv[1]
for root, dirs, files in walk(rootdir):
for filename in files:
if fnmatch(filename, '*.jpg'):
print(f'moving {filename} to {rootdir}')
origin = path.join(root, filename)
target = path.join(rootdir, 'Pictures')
move(origin, target)
print('done.')

Related

problem with moving files with extensions with shutil

I have the following code that should move files from one directory to another, the problem is when I run the code it just creates the folder and not moving any file to it. can anyone help me with that?
import os
import glob
import shutil
def remove_ext(list_of_pathnames):
return [os.path.splitext(filename)[0] for filename in list_of_pathnames]
path = os.getcwd()
os.chdir("D:\\TomProject\\Images\\")
os.mkdir("image_with_xml") # create a new folder
newpath = os.path.join("D:\\TomProject\\Images\\" ,"image_with_xml") #
made it os
independent...
list_of_jpegs = glob.glob(path+"\\*.jpeg")
list_of_xmls = glob.glob(path+"\\*.xml")
jpegs_without_extension = remove_ext(list_of_jpegs)
xmls_without_extension = remove_ext(list_of_xmls)
for filename in jpegs_without_extension:
if filename in xmls_without_extension:
shutil.move(filename + '.jpg', newpath) # move image to new path.
shutil.move(filename + '.xml', newpath)
You first use ".jpeg" as extension but then when you move mistakenly use ".jpg".

pathlib prints the current directory path

import os
import sys
import pathlib
for folderName,subfolders,filenames in os.walk('/'):
for filename in filenames:
# print(filename)
if filename.endswith('.pdf'):
path=pathlib.Path(filename).parent.absolute()
print("the file "+str(filename)+" has path "+str(path))
I want this script to look for all the pdf files in the os and i also want to print the path of the file but when i run the script it print the file names but prints the path in which i have the python script and not print the path to the pdf file.
This should work:
import os
import sys
import pathlib
for folderName,subfolders,filenames in os.walk('/'):
for filename in filenames:
if filename.endswith('.pdf'):
print(f"the file {filename} has path {folderName}")
You don't need pathlib for this one.
pathlib.Path(filename) will consider filename as a relative path, and thus its parent will be the folder from which the script was runned.

how to copy files and directory from source to destination using python

i want a python script that do these three tasks:
check if the path contains word file copied to specific destination
check if the path contains pdf files copied to specific destination
check if the path contains directory and copy the hole folder to
specific destination.
for this reason i am using the os.walk() to list the dirs and files of the path
and i am using shutil library to copy files and dirs.
code
import os
from distutils.dir_util import copy_tree
import shutil
from os import path
import datetime
def main():
src = "C:/Users/LT GM/Desktop/Python_files/"
dst2 = "C:/Users/LT GM/Desktop/"
for root,dirs,files in os.walk(src):
for name in files:
print("files: ",os.path.join(root,name))
for name in dirs:
copieddst = copy_tree(src,dst2)
print("directory: ",os.path.join(root,name))
print(" coppied directory :{0}".format(copieddst) )
# make a duplicate of an existing file
if path.exists(src):
# get the path to the file in the current directory
print("****")
src = path.realpath("pandas.pdf")
#seperate the path from the filter
head, tail = path.split(src)
print("path:" +head)
print("file:" +tail)
dst =str(datetime.date.today()) + tail
# nowuse the shell to make a copy of the file
shutil.copy(src, dst)
if __name__=="__main__":
main()
the problem is that i can copy the files or the content of the directory. not the hole directory and how to check if its pdf or doc files?
If you want to copy directory rather than file, then use shutil.copytree. In usage it is similiar to shutil.copy2, that is:
import shutil
shutil.copytree('mydir', 'mydircopy')
Note that by default dirs_exist_ok is False meaning that destination should not exist, when shutil.copytree is launched.

How to move from one directory to another and delete only '.html' files in python?

I attended an interview and they asked me to write a script to move from one directory to another and delete only the .html files.
Now I tried to do this at first using os.remove() . Following is the code:
def rm_files():
import os
from os import path
folder='J:\\Test\\'
for files in os.listdir(folder):
file_path=path.join(folder,files)
os.remove(file_path)
The problem I am facing here is that I cannot figure out how to delete only .html files in my directory
Then I tried using glob. Following is the code:
def rm_files1():
import os
import glob
files=glob.glob('J:\\Test\\*.html')
for f in files:
os.remove(f)
Using glob I can delete the .html files but still I cannot figure out how to implement the logic of moving from one directory to another.
And along with that can someone please help me figure out how to delete a specific file type using os.remove() ?
Thank you.
Either of these methods should work. For the first way, you could just string.endswith(suffix) like so:
def rm_files():
import os
from os import path
folder='J:\\Test\\'
for files in os.listdir(folder):
file_path=path.join(folder,files)
if file_path.endswith(".html"):
os.remove(file_path)
Or if you prefer glob, moving directories is fairly straightforward: os.chdir(path) like this:
def rm_files1():
import os
os.chdir('J:\\Test')
import glob
files=glob.glob('J:\\Test\\*.html')
for f in files:
os.remove(f)
Though it seems unnecessary since glob is taking an absolute path anyway.
Your problem can be described in the following steps.
move to specific directory. This can be done using os.chdir()
grab list of all *.html files. Use glob.glob('*.html')
remove the files. use os.remove()
Putting it all together:
import os
import glob
import sys
def remove_html_files(path_name):
# move to desired path, if it exists
if os.path.exists(path_name):
os.chdir(path_name)
else:
print('invalid path')
sys.exit(1)
# grab list of all html files in current directory
file_list = glob.glob('*.html')
#delete files
for f in file_list:
os.remove(f)
#output messaage
print('deleted '+ str(len(file_list))+' files in folder' + path_name)
# call the function
remove_html_files(path_name)
To remove all html files in a directory with os.remove() you can do like this using endswith() function
import sys
import os
from os import listdir
directory = "J:\\Test\\"
test = os.listdir( directory )
for item in test:
if item.endswith(".html"):
os.remove( os.path.join( directory, item ) )

How to copy a file in a zipfile into a certain directory?

I need only one subfile in each of 500 zipfiles, the paths are the same, like:
120132.zip/A/B/C/target_file
212332.zip/A/B/C/target_file
....
How can I copy all these target files into one directory? Keeping the entire paths in the new directory will be the best, which I mean is:
target_dir/
120132/A/B/C/target_file
212332/A/B/C/target_file
......
I tried it with Python modules zipfile and shutil
However, copyfile from shutil takes the entire path as argument but when I tried to directly copy the target file it will raise filenotfind error. When unzipped by the zipfile.Zipfile, the target file will be accessible but copyfile becomes invalid.
How can I do this correctly and efficiently ?
ZipFile.extract accepts optional path specifying into which directory it will extract file:
import os
import zipfile
zip_filepath = ['120132.zip', '212332.zip', ...] # or glob.glob('...zip')
target_dir = '/path/to/target_dir'
for path in zip_filepath:
with zipfile.ZipFile(path) as zf:
dirname = os.path.join(
target_dir, os.path.splitext(os.path.basename(path))[0]
)
zf.extract('A/B/C/target_file', path=dirname)

Categories