Removing a directory using shutil module - python

I'm trying to remove a directory using python but I do not want to recursively remove the whole directory path in the process: i.e
/home/dir/dir/dirtoberemoved
So I don't want to remove anything at a higher level just the one directory and all its contents. I've been looking on stackoverflow to research this question and most answers have included using the shutil module which I am unfamiliar with, looking at the python documentation for the module it says 'Delete an entire directory tree'
If I do something like this:
if os.path.exists("/home/dir/dir/dirtoberemoved");
shutil.rmtree("/home/dir/dir/dirtoberemoved");
or
shutil.rmtree("/dirtoberemoved");
Will the entire path be removed? If so is there any good way just to delete one non-empty directory in python without deleting higher level directories?

You need to specify the whole path to the directory to be removed. Only the last part of the path will be deleted, the /home/dir/dir/ part will be untouched.
The deletion refers to any sub-directories contained within the named path, so if there is a /home/dir/dir/dirtoberemoved/foo sub-directory it'll be removed together with it's parent.

Related

Navigating directories

After getting the path to the current working directory using:
cwd = os.getcwd()
How would one go up one folder: C:/project/analysis/ to C:/project/ and enter a folder called data (C:/project/data/)?
In general it a bad idea to 'enter' a directory (ie change the current directory), unless that is explicity part of the behaviour of the program.
In general to open a file in one directory 'over from where you are you can do .. to navigate up one level.
In your case you can open a file using the path ../data/<filename> - in other words use relative file names.
If you really need to change the current working directory you can use os.chdir() but remember this could well have side effects - for example if you import modules from your local directory then using os.chdir() will probably impact that import.
As per Python documentation, you could try this:
os.chdir("../data")

How can I delete contents of a folder but keep the folder?

I have seen several questions here, but all of them seem to delete the folder as well.
How can I delete only the contents of a particular folder, but keep the folder itself.
Preferably for two conditions:
Contents
Deletes recursively under all all subfolders. But keeps the main folder.
import os
def functToDeleteItems(fullPathToDir):
for itemsInDir in os.listdir(fullPathToDir):
if os.path.isdir(os.path.join(fullPathToDir, itemsInDir)):
functToDeleteItems(os.path.isdir(os.path.join(fullPathToDir, itemsInDir)))
else:
os.remove(os.path.join(fullPathToDir,itemsInDir))
Here function "functToDeleteItems" will take one argument that is "fullPathToDir" which will contain full path of the folder whose content you wan to delete. It will recursively call itself it if find any folder inside it and if found any file then delete it.

How do I create directories in Python given a list of files with paths that may or may not exist?

How do I create directories in Python given a list of files with paths that may or may not exist?
I am downloading some files from s3 that may or may not exist in a certain directory. Based upon these keys that represent a potentially deeply nested directory that may or may not exist.
So based upon the key /a/number/of/nested/dirs/file.txt how can I created /a/number/of/nested/dirs/ if they do not exist and do it in a way that doesn't take forever to check for each file in the list.
I am doing this because if the local parent directories do not already exist get_contents_to_filename breaks.
My Final Solution Using Answer:
for file_with_path in files_with_paths:
try:
if not os.path.exists(file_with_path):
os.makedirs(file_with_path)
site_object.get_contents_to_filename(file_with_path)
except:
pass
Simply use os.makedirs(). This will create all intermediate directories if needed.
Recursive directory creation function. Like mkdir(), but makes all
intermediate-level directories needed to contain the leaf directory.
Raises an error exception if the leaf directory already exists or
cannot be created. The default mode is 0777 (octal). On some systems,
mode is ignored. Where it is used, the current umask value is first
masked out.

Delete multiple directories in python

In python, I understand that I can delete multiple files with the same name using the following command for eg:
for f in glob.glob("file_name_*.txt"):
os.remove(f)
And that a single directory can be deleted with shutil.rmtree('/path/to/dir') - and that this command will delete the directory even if the directory is not empty. On the other hand, os.rmdir() needs that the directory be empty.
I actually want to delete multiple directories with the same name, and they are not empty. So, I am looking for something like
shutil.rmtree('directory_*')
Is there a way to do this with python?
You have all of the pieces: glob() iterates, and rmtree() deletes:
for path in glob.glob("directory_*"):
shutil.rmtree(path)
This will throw OSError if one of the globbed paths names a file, or for any other reason that rmtree() can fail. You can add error handling as you see fit, once you decide how you want to handle the errors. It doesn't make sense to add error handling unless you know what you want to do with the error, so I have left error handling out.

python zipfile basename

I have some homework that I am trying to complete. I don't want the answer. I'm just having trouble in starting. The work I have tried is not working at all... Can someone please just provide a push in the right direction. I am trying to learn but after trying and trying I need some help.
I know I can you os.path.basename() to get the basename and then add it to the file name but I can't get it together.
Here is the assignment
In this project, write a function that takes a directory path and creates an archive of the directory only. For example, if the same path were used as in the example ("c:\\xxxx\\Archives\\archive_me"), the zipfile would contain archive_me\\groucho, archive_me\\harpo and archive_me\\chico.
The base directory (archive_me in the example above) is the final element of the input, and all paths recorded in the zipfile should start with the base directory.
If the directory contains sub-directories, the sub-directory names and any files in the sub-directories should not be included. (Hint: You can use isfile() to determine if a filename represents a regular file and not a directory.)
Thanks again any direction would be great.
It would help to know what you tried yourself, so I'm only giving a few pointers to methods in the standard libraries:
os.listdir to get the a list of files and folders under a given directory (beware, it returns only the file/folder name, not the full path!)
os.path.isfile as mentioned in the assignment to check if a given path represents a file or a folder
os.path.isdir, the opposite of os.path.isfile (thanks inspectorG4adget)
os.path.join to join a filename with the basedir without having to worry about slashes and delimiters
ZipFile for handling, well, zip files
zipFile.write to write the files found to the zip
I'm not sure you'll need all of those, but it doesn't hurt knowing they exist.

Categories