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.
Related
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".
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
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.
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.')
I am aiming to create a function that does the following:
Declare a path with a file, not just a folder. e.g. 'C:/Users/Lampard/Desktop/Folder1/File.py'
Create a folder in same folder as the declared file path - Calling it 'Archive'
Cut the file and paste it into the new folder just created.
If the folder 'Archive' already exists - then simply cut and paste the file into there
I have spent approx. 15-20min going through these:
https://www.programiz.com/python-programming/directory
Join all except last x in list
https://docs.python.org/3/library/pathlib.html#operators
And here is what I got to:
import os
from pathlib import Path, PurePath
from shutil import copy
#This path will change every time - just trying to get function right first
path = 'C:/Users/Lampard/Desktop/Folder1/File.py'
#Used to allow suffix function
p = PurePath(path)
#Check if directory is a file not a folder
if not p.suffix:
print("Not an extension")
#If it is a file
else:
#Create new folder before last file
#Change working directory
split = path.split('/')
new_directory = '/'.join(split[:-1])
apply_new_directory = os.chdir(new_directory)
#If folder does not exist create it
try:
os.mkdir('Archive')#Create new folder
#If not, continue process to copy file and paste it into Archive
except FileExistsError:
copy(path, new_directory + '/Archive/' + split[-1])
Is this code okay? - does anyone know a simpler method?
Locate folder/file in path
print [name for name in os.listdir(".") if os.path.isdir(name)]
Create path
import os
# define the name of the directory to be created
path = "/tmp/year"
try:
os.mkdir(path)
except OSError:
print ("Creation of the directory %s failed" % path)
else:
print ("Successfully created the directory %s " % path)
To move and cut files you can use this library
As you're already using pathlib, there's no need to use shutil:
from pathlib import Path
path = 'C:/Users/Lampard/Desktop/Folder1/File.py' # or whatever
p = Path(path)
target = Path(p.with_name('Archive')) # replace the filename with 'Archive'
target.mkdir() # create target directory
p.rename(target.joinpath(p.name)) # move the file to the target directory
Feel free to add appriopriate try…except statements to handle any errors.
Update: you might find this version more readable:
target = p.parent / 'Archive'
target.mkdir()
p.rename(target / p.name)
This is an example of overloading / operator.