How do I delete a file or folder in Python?
os.remove()
removes a file.os.rmdir()
removes an empty directory.shutil.rmtree()
deletes a directory and all its contents.
Path
objects from the Python 3.4+ pathlib
module also expose these instance methods:
pathlib.Path.unlink()
removes a file or symbolic link.pathlib.Path.rmdir()
removes an empty directory.
How to delete the contents of a folder?
import os, shutil
folder = '/path/to/folder'
for filename in os.listdir(folder):
file_path = os.path.join(folder, filename)
try:
if os.path.isfile(file_path) or os.path.islink(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except Exception as e:
print('Failed to delete %s. Reason: %s' % (file_path, e))
How to permanently delete a file in python 3 and higher?
os.remove
is already what you're looking for. It doesn't send things to Trash. It just deletes them.
How do I delete a specified number of files in a directory in Python?
You simply have to iterate correctly in the range:
files = os.listdir('path/to/your/folder')
for file in files[:11]:
os.remove(file)
in this way you are iterating through a list containing the first 11 files.
If you want to remove random files, you can use:
from random import sample
files = os.listdir('path/to/your/folder')
for file in sample(files,11):
os.remove(file)
For folder in dir, enter it and delete files if condition is met
You should spend time to make this function more efficient. However, it will do what you want.
import os
def deleteNonPyFiles(parent_dir):
no_delete_kw = '.py'
for (dirpath, dirnames, filenames) in os.walk(parent_dir):
for file in filenames:
if no_delete_kw not in file:
os.remove(f'{dirpath}/{file}')
deleteNonPyFiles('C:/User/mydirpath')
Python remove files from folder which are not in list
for filename in os.listdir(path):
print(filename)
if filename not in file_name:
os.remove(filename)
Deleting files of specific extension using * in Python
from pathlib import Path
for filename in Path(".").glob("temp*.txt"):
filename.unlink()
How delete all files in a folder except last 5 items with Python
User os.listdir to get the name of the files. As this returns an iterator you can easily sort the way you want in python itself. then use list indexing to keep the last five ones.
then use os.remove to remove the files
import os
for filename in sorted(os.listdir("foldername"))[:-5]:
filename_relPath = os.path.join("foldername",filename)
os.remove(filename_relPath)
Related Topics
How to Change a Global Variable from Within a Function
Change Working Directory in Shell with a Python Script
Python Convert Microsoft Office Docs to Plain Text on Linux
Linux/Python: Encoding a Unicode String for Print
How to Programmatically Edit Excel Sheets
How to Default Python3.8 on My MAC Using Homebrew
Google Cloud Sdk: Set Environment Variable_ Python --> Linux
Python: Complexity of Os.Path.Exists with a Ext4 Filesystem
How to Write Dataframe to Postgres Table
Overriding Special Methods on an Instance
Environment Variables When Script Run by Cron
Running Process of Remote Ssh Server in the Background Using Python Paramiko
Permission Denied When Executing Python File in Linux