what does the "shutil.rmtree" do? - python

I saw the following codes on website:
import tempfile
import shutil
dirpath = tempfile.mkdtemp()
# ... do stuff with dirpath
shutil.rmtree(dirpath)
I know that "shutil.rmtree" is delete an entire directory tree. But why delete the directory just after it was built?
I fond one answer said:"If you use this in a test be sure to remove (shutil.rmtree) the directory because it's not automatically deleted after use." But after I tried, even without "shutil.rmtree", the directory I just built will be deleted after restart computer.
So what does the "shutil.rmtree" do?

The directory is created in a temporary location that your system may choose to delete at some point in the future.
If you know you're done with the temporary directory created, you can remove it yourself using shutil.rmtree immediately.

Related

Been trying to copy folders and files using shutil.tree() function in python but brings FileExistsError

I have tried to use shutil module in python. The shutil.copytree fails to copy folders and brings FileExistsError. I have tried it using different files but it still fails.Please check
import shutil
from pathlib import Path
p = Path(r"C:\Users\rapid\OneDrive\Desktop")
shutil.copytree(p/"folder_1", p/"folder_2")
Please check for the error image
I tried the code myself and works fine the first time.
After the destination folder (in your case folder_2) already created shutil can't create it again and it fails. So you can either delete the destination folder manually or using shutil.rmtree.
Good Luck!
All credit to Timus. He provided the solution on the comment section. Just used
shutil.copytree(p/"folder_1", p/"folder_2", dirs_exist_ok=True)
It works fine. Thanks Timux

Why does my code delete everything in the folder?

I wrote code to detect all the .exe files in a directory but instead it deletes everything in the folder. How can I change the code to make it delete only the .exe files?
import os
import shutil
dir_name = "/Users/plapl/Downloads/"
source = os.listdir("/Users/plapl/Downloads/")
for files in source:
if files.endswith(".exe"):
shutil.rmtree(dir_name, files)
You can only delete directories with shutil.rmtree but not files (See https://docs.python.org/3/library/shutil.html#shutil.rmtree).
You should use pathlib or os instead.
os.remove(f'{dir_name}/{files}')
pathlib.Path(f'{dir_name}/{files}').unlink()
shutil.rmtree removes the entire directory specified by its first argument. The second argument to shutil.rmtree is ignore_errors, telling the function whether to ignore errors that occur. It is not a file to remove.
shutil.rmtree is a completely inappropriate tool for the job you want to do. You need something like os.remove.

how to `shutil.move` with readonly files across drives

At least on windows, shutil.move a folder containing readonly files to another drive will fail. It fails because move is implemented with a copy followed by a rmtree. In the end, it's the rmtree trying to delete non writable files.
Currently I work around it by first setting the stat.S_IWUSER for all (nested) files, but now I should still restore the original stat afterwards:
def make_tree_writable(source_dir):
for root, dirs, files in os.walk(source_dir):
for name in files:
make_writable(path.join(root, name))
def make_writable(path_):
os.chmod(path_, stat.S_IWUSR)
def movetree_workaround(source_dir, target_dir):
make_tree_writable(source_dir)
shutil.move(source_dir, target_dir)
So I wonder: is this the way? Is there a shutil2 in the making that I could use? Can I be of any help there?
You can do that in two steps: first, use shutil.copytree() to copy the full directory and file structure with appropriate permissions. Then you can change permissions of the source to make sure you have rights to delete stuff, and use shutil.rmtree() to remove the old source.

How to copy all subfolders into an existing folder in Python 3?

I am sure I am missing this, as it has to be easy, but I have looked in Google, The Docs, and SO and I can not find a simple way to copy a bunch of directories into another directory that already exists from Python 3?
All of the answers I find recommend using shutil.copytree but as I said, I need to copy a bunch of folders, and all their contents, into an existing folder (and keep any folders or that already existed in the destination)
Is there a way to do this on windows?
I would look into using the os module built into python. Specifically os.walk which returns all the files and subdirectories within the directory you point it to. I will not just tell you exactly how to do it, however here is some sample code that i use to backup my files. I use the os and zipfile modules.
import zipfile
import time
import os
def main():
date = time.strftime("%m.%d.%Y")
zf = zipfile.ZipFile('/media/morpheous/PORTEUS/' + date, 'w')
for root, j, files in os.walk('/home/morpheous/Documents'):
for i in files:
zf.write(os.path.join(root, i))
zf.close()
Hope this helps. Also it should be pointed out that i do this in linux, however with a few changes to the file paths it should work the same

Python: Checking for directories in CVS Repository

I'm wondering if I could use
os.path.isdir(sourceDirectory)
to check for the existence of a directory in a CVS repository. Similarly, if the os.walk method would work for a repository directory. If not, what would be a good way to approach this problem?
os handles this very well already! Isn't python wonderful?
The following example searches for a file named CSV in the root directory of your machine, but you can point it to any directory you like, including a relative path.
def file_exists():
path = '/' # the path you want to search for the file in
target = 'CSV' # name of the directory
if target in os.list:
#do whatever you were going to do once you confirmed that this file exists
return True
return False

Categories