I am creating a login system and I want to reset the info whenever the system is restarted. I have stored my information in text files in a directory called accounts
. There are text files and subdirectories in the data/accounts
directory.
I thought that I can use os.remove
, but it does not work. So far, I have tried this.
import os
def infoReset():
os.remove("data/accounts/")
But it just gives me back an "operation not permitted"
error. How can I delete the data/accounts
directory and its contents?
2 Answers 2
Consider using a TemporaryDirectory, which will be automatically removed after you're done with it. This prevents bugs related to your manual and potentially insecure management of a directory.
According to the documentation,
On completion of the context or destruction of the temporary directory object the newly created temporary directory and all its contents are removed from the filesystem.
The directory name can be retrieved from the name attribute of the returned object. When the returned object is used as a context manager, the name will be assigned to the target of the as clause in the with statement, if there is one.
The directory can be explicitly cleaned up by calling the cleanup() method.
Here's an abridged example that applies to your use case:
import tempfile
# At the beginning of your program, create a temporary directory.
tempdir = tempfile.TemporaryDirectory()
...
# Later, remove the directory and its contents.
tempdir.cleanup()
Alternatively, depending on how feasible this would be in your project, use a context manager.
import tempfile
with tempfile.TemporaryDirectory() as tmpdirname:
# Write files in the directory...
# ...
# As soon as your exit this block, the directory is automatically cleaned up.
Comments
os.remove()
is for files, not directories. os.rmdir()
is for removing directories, but only empty directories. To delete a directory and its contents, use shutil.rmtree()
.
import shutil
def infoReset():
shutil.rmtree("data/accounts/")
os.remove()
will remove a file.os.rmdir()
will remove an empty directory.shutil.rmtree()
will delete a directory and all its contents.OSError
is raised. Usermdir()
to remove directories."