Python - Paste document to each folder in directory - python

I have an annual file located on our netwrok that contains sub-folders based on each week of the year. I am trying to write a script that will copy a "Template" document saved on my desktop, then iterate through the annual file, and paste the Template into each weekly sub-folder.
I have a script that is generating a "PermissionError: [Errno 13] Permission denied:" though I am not sure why, and therefore not sure what to do about it.
import os
import shutil
myPath = r"""K:\PROCESS\YEAR"""
myDocument = r"""C:\Users\me.domain\OneDrive - Co Name\Desktop\Template.xlsx"""
for filename in os.listdir(myPath):
with open(os.path.join(myPath,filename)) as myFile:
copyfile(myDocument, myFile)
Error is,
PermissionError: [Errno 13] Permission denied: ‘K:\PROCESS\YEAR\WEEK 1’
# line 'with open(os.path.join(myPath,filename)) as myFile:'
I tried moving the target document to the program root and modified the script based on some sugestions as seen below.
import os
from shutil import copy2
my_doc_path = "Template.xlsx"
myPath = "K:\PROCESS\YEAR"
for directory in os.listdir(myPath):
copy2(my_doc_path, directory)
I am no longer receiving any errors; however, the target document is not being coppied to the target directory. Instead, a nondescript "file" with the target directory name is being created in the program root as seen in the image below.
What ended up working:
import os
from shutil import copy
my_doc_path = "Template.xlsx"
myPath = "K:\PROCESS\YEAR"
for directory in os.listdir(myPath):
target_directory = myPath + '\\' + directory
check_file = target_directory + '\\' + my_doc_path
if not os.path.exists(check_file):
copy(my_doc_path, target_directory)

Instead of opening a file, try to copy your file in the target folders.
from shutil import copy
my_doc_path = "/here/is/my/doc/path.xlsx"
myPath = "K:\PROCESS\YEAR"
for directory in os.listdir(myPath):
copy(my_doc_path, directory)
Or if you need also the metadata:
from shutil import copy2
my_doc_path = "/here/is/my/doc/path.xlsx"
myPath = "K:\PROCESS\YEAR"
for directory in os.listdir(myPath):
copy2(my_doc_path, directory)
Why copy/copy2 instead of copyfile? take a look at this comment

The document name needed to be appended to myPath variable. I incorrectly assumed the copy2() function was looking for the path to save the document to, I didnt realize it required the full destination path including the document itself.
Thanks for the feedback everyone, it got me pointed in the right direction.

Related

Move files from subfolders to another folder

I want to move all the files from multiple subdirectories to another folder in the same directory as the parent folder but get the following error:
FileNotFoundError: [Errno 2] No such file or directory: '/content/drive/MyDrive/Dev/FaceRec/lfw/Emmit_Smith/Emmit_Smith_0001.jpg' -> '/content/drive/MyDrive/Dev/FaceRec/negatives/Emmit_Smith_0001.jpg'
this is my code:
for directory in os.listdir('/content/drive/MyDrive/Dev/FaceRec/lfw'):
for file in os.listdir(os.path.join('/content/drive/MyDrive/Dev/FaceRec/lfw', directory)):
path = os.path.join('/content/drive/MyDrive/Dev/FaceRec/lfw', directory, file)
new_path = os.path.join('/content/drive/MyDrive/Dev/FaceRec/negatives', file)
os.replace(path, new_path)
Thank you for the help in advance
Try the following:
import os
import glob
import shutil
src_path = '/content/drive/MyDrive/Dev/FaceRec/lfw'
dest_path = src_path.replace('lfw', 'negatives')
flist = glob.glob(os.path.join(src_path, '*/*'))
for fname in flist:
shutil.move(fname, fname.replace(os.path.dirname(fname), dest_path))
Why this is better:
The glob functions helps to avoid one for loop and also prevents from repeatedly joining the paths together
shutil.movecreates the destination directory for you if it does not exist. Also it can handle symlinks.
By putting the paths in variables we can minimize copy past errors

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.

Python - I zip some folders with subfolders but it zips twice.

I have written a script. It finds the current path and changes the path and zips. Then I want that it just find the zip file copy it to another directory and at the end removes the content of the folder. But it zips once and zips again the whole folders and zip-file. The intial situation is as in Figure 1.
The script is like this:
import os
import zipfile
import shutil
import glob
Pfad = os.getcwd()
newPfad = 'D'+ Pfad[1:]
Zip_name=os.path.basename(os.path.normpath(Pfad))
shutil.make_archive(Zip_name, 'zip', Pfad)
if not os.path.exists(newPfad):
os.makedirs(newPfad)
dest_dir=newPfad
files = glob.iglob(os.path.join(Pfad, "*.zip"))
for file in files:
if os.path.isfile(file):
shutil.copy2(file, dest_dir)
shutil.rmtree(Pfad)
And finally the result is illustrated in the following figure.
The batch file is just for running the python script.
How can I get the following desired situation?
The issue is that zip file is created prior to listing the directory contents, therefore empty zip file is added to. Create archive in the parent directory and then move it. Moving a file or directory is cheap and atomic.
import os
import shutil
cwd = os.path.abspath(os.path.curdir)
zip_target = os.path.join(cwd, os.path.basename(cwd)) + '.zip'
zip_source = shutil.make_archive(cwd, 'zip')
os.rename(zip_source, zip_target)

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)

error moving file with shutil

I am trying to create a simple function that finds files that begin with a certain string and then move them to a new directory but I keep getting the following kinds of errors from shutil "IOError: [Errno 2] No such file or directory: '18-1.pdf'", even though the file exists.
import os
import shutil
def mv_files(current_dir,start):
# start of file name
start = str(start)
# new directory ro move files in to
new_dir = current_dir + "/chap_"+ start
for _file in os.listdir(current_dir):
# if directory does not exist, create it
if not os.path.exists(new_dir):
os.mkdir(new_dir)
# find files beginning with start and move them to new dir
if _file.startswith(start):
shutil.move(_file, new_dir)
Am I using shutil incorrectly?
correct code:
import os
import shutil
def mv_files(current_dir,start):
# start of file name
start = str(start)
# new directory ro move files in to
new_dir = current_dir + "/chap_" + start
for _file in os.listdir(current_dir):
# if directory does not exist, create it
if not os.path.exists(new_dir):
os.mkdir(new_dir)
# find files beginning with start and move them to new dir
if _file.startswith(start):
shutil.move(current_dir+"/"+_file, new_dir)
It looks like you aren't giving the full path to shutil.move. Try:
if _file.startswith(start):
shutil.move(os.path.abspath(_file), new_dir)
If that fails, try printing _file, and new_dir along with the result of os.getcwd() and adding them to your answer.

Categories