My Session to create a Chrome Profile cleaner script

Part of: AI Learning Series Here
Subscribe to JorgeTechBits newsletter
So after I finished my previous blog post: How to Back Up All Chrome Profiles from Your Computer (at about 8:30p) I wondered if I could build a quick script to clean up the profiles on my device.
I was already using perplexity to help me as an editor of that blog post so I asked it a couple more questions, and then requested a Product requirements document which I then took into Gemini Pro for creation of the script and documentation.
Hint: It took me more time to create this blog post than to create and publish this script to GitHub!
Absolutely amazing if you think about it!
Hope this helps!
Want more updates? Subscribe to my JorgeTechBits newsletter
Source code and full result on GitHub at: here
This is my full session:
Perplexity.ai Session:
Are there any tools out there that will automate the clean up of the profiles
There are some tools and extensions that help automate managing and cleaning up Chrome profiles, though fully automated cleanup of cache, cookies, and history across all profiles is still limited. Here are notable options based on recent information:
- Profile Manager Pro (Chrome Extension):
This extension focuses on advanced multi-account management, allowing you to save, switch, and manage multiple profiles and sessions easily. It offers features like smart cookie management, automatic session saving, and instant profile switching without repeated logins. While it helps manage cookies and sessions per profile, it does not fully automate clearing cache or browsing history but does simplify cookie cleanup and profile backups2. - Reoon Chrome Profile & Session Manager (Software):
This tool lets you create and manage hundreds of isolated Chrome profiles and sessions from a single dashboard. It securely stores cookies, caches, and browser history per profile and supports importing/exporting profiles. It’s useful for managing multiple accounts and sessions, especially in social media marketing or testing scenarios. However, it may not fully automate cache/history cleanup but helps keep profiles isolated and manageable6. - Chrome Enterprise Cloud Management:
For organizations, Google offers cloud-based browser management tools that provide centralized control over Chrome settings and profiles, including policies that can help manage data retention and cleanup. This is more suited for IT admins managing many users rather than individual users13. - Manual or Scripted Cleanup:
Currently, for individual users, cleaning cache, cookies, and history still requires manual action per profile via Chrome’s settings. Some advanced users automate cleanup using scripts or third-party system cleaners that target Chrome’s profile folders, but these require technical knowledge and caution to avoid data loss.
Summary
While tools like Profile Manager Pro and Reoon greatly simplify managing multiple Chrome profiles, sessions, and cookies, fully automated cleanup of all browsing data (cache, cookies, history) across all profiles simultaneously is not widely available as a turnkey solution. Manual cleanup remains the most reliable method for thorough cache and history clearing per profile.
If you manage many profiles regularly, these tools can save time by streamlining session and cookie management and backing up profiles, but combining them with periodic manual cleanup is recommended for optimal performance and privacy.
- https://chromeenterprise.google/products/cloud-management/
- https://chromewebstore.google.com/detail/profile-manager-pro/omnafjdgigipejaajbnlopdjifgknogj
- https://support.google.com/chrome/a/answer/9025411
- https://multilogin.com/blog/how-to-manage-multiple-chrome-profiles/
- https://help.taskmagic.com/faq/4CTzHMYGRpSomBeZsSgB4b/how-do-i-set-up-and-attach-my-chrome-profile-to-an-automation-at-the-beginning-and-why-do-i-need-the-chrome-profile/vJQLBFgwhgfHR4PJ9Mj5Fy
- https://www.reoon.com/chrome-profile-manager/
- https://docs.citrix.com/en-us/profile-management/current-release/integrate/google-chrome.html
- https://www.neovasolutions.com/2024/06/13/automating-chrome-with-existing-profiles-using-playwright-and-typescript/
I wonder if you can write a script or application to do this
Yes, it is possible to write a script or application to automate the cleanup of Chrome profiles. Several approaches and examples already exist:
- PowerShell/Bash Scripts:
Scripts can be created to delete or clean specific files (like cache, history, cookies) within each Chrome profile folder. For example, PowerShell scripts can target theCache
,Media Cache
, and other data folders inside each profile directory and remove their contents automatically5. Bash scripts on Mac or Linux can userm
commands to delete history, cookies, and cache files for all user profiles68. - Profile Cleaner Tools:
Open-source tools like profile-cleaner help reduce the size of browser profiles by optimizing their internal databases, although they focus more on SQLite maintenance than full data deletion3. - Group Policy/Registry (Windows) or Configuration Profiles (Mac):
For enterprise or managed environments, Chrome supports policies that can automatically clear browsing data (history, cookies, cache, etc.) on exit, which can be set via Windows Group Policy, registry edits, or Mac configuration profiles7. This is more suitable for IT administrators managing multiple machines. - Sample Script Example (Windows PowerShell): powershell
$UserData = "$($env:LOCALAPPDATA)\Google\Chrome\User Data" $Profiles = Get-ChildItem $UserData | Where-Object { $_.PSIsContainer -and ($_.Name -eq "Default" -or $_.Name -like "Profile*") } foreach ($Profile in $Profiles) { Remove-Item -Recurse -Force "$($Profile.FullName)\Cache" Remove-Item -Recurse -Force "$($Profile.FullName)\Media Cache" # Add more folders as needed }
This script will clear cache folders for all Chrome profiles on a Windows machine5. - Sample Script Example (macOS/Linux Bash): bash
for profile in ~/Library/Application\ Support/Google/Chrome/*/; do rm -rf "${profile}Cache" "${profile}Media\ Cache" # Add more files/folders as needed done
This will clear cache for all profiles on macOS8.
Note:
- Scripts must be run when Chrome is closed to avoid file lock issues.
- Always back up your data before running cleanup scripts to prevent accidental data loss.
- For less technical users, manual cleanup or using Chrome’s built-in settings is safer.
If you want a custom script tailored to your OS and cleanup needs, let me know your platform and what data you want to remove, and I can help draft one for you.
- https://superuser.com/questions/405797/clean-chrome-profile
- https://www.reddit.com/r/chrome/comments/1eanbqm/chrome_uninstall_cleanup_utility_or_3rdparty/
- https://github.com/graysky2/profile-cleaner
- https://stackoverflow.com/questions/70742463/delete-multiple-chrome-profile-automatically
- https://github.com/fleetcaptain/clean-profile/blob/master/clean-profile.ps1
- http://www.macrodroidforum.com/index.php?threads%2Fhow-to-make-chrome-automatic-history-deletion-script.3767%2F
- https://support.google.com/chrome/a/answer/10686330
- https://community.jamf.com/t5/jamf-pro/script-to-delete-chrome-prefs-folder-for-all-users/m-p/148622
can you write a requirements document that explains what is needed
Absolutely! Here’s a sample requirements document for an application or script designed to automate the cleanup of Chrome profiles on a local machine.
Requirements Document
Project: Chrome Profile Cleanup Automation
Date: June 12, 2025
1. Purpose
The purpose of this project is to develop a script or application that automates the cleanup of browsing data (cache, cookies, history, etc.) for all Google Chrome profiles on a user’s computer. This tool will help users reduce disk usage, improve browser performance, and protect privacy by removing unnecessary or sensitive data across all profiles without manual intervention.
2. Scope
- The tool will identify all Chrome profile folders within the Chrome User Data directory.
- It will delete or clear specific types of browsing data (e.g., cache, cookies, history, downloads) in each profile.
- The tool will support Windows, macOS, and Linux environments.
- The tool will provide options for users to select which data types to clean.
- The tool will ensure Chrome is not running before performing cleanup to prevent data corruption.
3. Functional Requirements
3.1 Profile Detection
- Automatically locate the Chrome User Data directory based on the operating system.
- Detect all existing profile folders (e.g.,
Default
,Profile 1
,Profile 2
, etc.).
3.2 Data Cleanup
- Provide options to clean the following data types per profile:
- Cache
- Cookies
- Browsing history
- Download history
- Autofill form data
- Saved passwords (optional, with warning)
- Site settings
- Perform cleanup by deleting relevant files or folders within each profile directory.
3.3 User Interface (if applicable)
- Command-line interface (CLI) or graphical user interface (GUI) for user interaction.
- Allow users to select which data types to clean.
- Display a summary of actions to be taken and request user confirmation before proceeding.
3.4 Safety & Backup
- Check if Chrome is running and prompt the user to close it before proceeding.
- Optionally, create a backup of profile data before cleaning.
- Provide warnings before deleting sensitive data (e.g., saved passwords).
3.5 Logging & Reporting
- Log actions taken for each profile.
- Report the amount of data cleaned per profile.
4. Non-Functional Requirements
- Cross-Platform Compatibility: Must work on Windows, macOS, and Linux.
- Performance: Should complete cleanup within a reasonable time, even with multiple profiles.
- Reliability: Must not corrupt or damage Chrome profiles.
- Usability: Easy to use for non-technical users (especially if a GUI is provided).
- Security: Must not transmit any user data externally.
5. Constraints
- The tool must be run with appropriate user permissions to access Chrome’s profile directories.
- Chrome must be closed during cleanup to avoid file access conflicts.
- Some data (like cookies or passwords) may be encrypted and not fully removable without affecting profile integrity.
6. Out of Scope
- Managing or cleaning profiles for browsers other than Google Chrome.
- Cloud-based or remote profile management.
- Enterprise-level deployment and policy management.
7. Future Enhancements (Optional)
- Scheduling automatic cleanups.
- Integration with other browsers (Edge, Chromium, etc.).
- Advanced reporting and analytics on browsing data.
8. References
End of Document
What specific functionalities should the requirements document specify for profile cleanup?
To ensure a Chrome profile cleanup tool is effective and user-friendly, the requirements document should specify the following specific functionalities for profile cleanup:
1. Profile Discovery
- Automatically detect and list all Chrome user profiles within the User Data directory on the target operating system (Windows, macOS, Linux).
2. Data Type Selection
- Allow users to choose which types of data to clean for each profile, including:
- Cache
- Cookies
- Browsing history
- Download history
- Autofill form data
- Site settings
- Saved passwords (with explicit warning and confirmation)
3. Selective or Bulk Cleanup
- Support cleaning:
- All profiles at once (bulk cleanup)
- Selected individual profiles (user can choose which profiles to clean)
4. Safety Checks
- Detect if Chrome is currently running and prompt the user to close it before proceeding.
- Option to back up profile data before cleanup begins.
5. User Confirmation
- Display a summary of the selected cleanup actions and request user confirmation before executing any deletions.
6. Execution of Cleanup
- Delete or securely erase the selected data types from each targeted profile directory.
- Ensure system and special profiles are not affected (e.g., built-in/system profiles should be excluded from deletion1).
7. Logging and Reporting
- Log all actions taken, including:
- Which profiles were cleaned
- What data types were deleted
- Any errors or skipped actions
- Provide a summary report to the user after cleanup.
8. Custom Scheduling (Optional/Future)
- Allow users to schedule regular automatic cleanups.
9. Cross-Platform Support
- Ensure all functionalities work across Windows, macOS, and Linux environments.
10. Extensibility
- Design the tool to allow for future addition of new data types or integration with other browsers.
These functionalities should be explicitly stated in the requirements document to guide development and ensure the tool meets user needs for both productivity and privacy.241
https://www.scalablepath.com/project-management/product-requirements-document-guide
https://www.reddit.com/r/sysadmin/comments/16zlip2/user_profile_cleanup/
https://www.itjungle.com/2012/08/08/fhg080812-story03/
https://www.jetbrains.com/help/rider/Code_Cleanup__Index.html
https://joshroark.com/sharepoint-the-complete-guide-to-user-profile-cleanup-part-4-2016/
https://sites.nationalacademies.org/cs/groups/pgasite/documents/webpage/pga_179129.pdf
https://intersys.co.uk/2021/03/24/this-is-how-to-write-a-foolproof-user-requirements-specification/
PLease add to the requirements document and make each optional. Also can you please specify this feature as the default behaviour: app to go trhough all profiles and list what it will do, but do not erase or change unless the explicit flag. List how much space it will save
Requirements Document
Project: Chrome Profile Cleanup Automation
Date: June 12, 2025
1. Purpose
The purpose of this project is to develop a script or application that automates the cleanup of browsing data (cache, cookies, history, etc.) for all Google Chrome profiles on a user’s computer. This tool will help users reduce disk usage, improve browser performance, and protect privacy by removing unnecessary or sensitive data across all profiles without manual intervention.
2. Scope
- The tool will identify all Chrome profile folders within the Chrome User Data directory.
- It will analyze and, upon explicit user command, delete or clear specific types of browsing data (e.g., cache, cookies, history, downloads) in each profile.
- The tool will support Windows, macOS, and Linux environments.
- The tool will provide options for users to select which data types to clean.
- The tool will ensure Chrome is not running before performing cleanup to prevent data corruption.
3. Functional Requirements
3.1 Profile Detection (Required)
- Automatically locate the Chrome User Data directory based on the operating system.
- Detect all existing profile folders (e.g.,
Default
,Profile 1
,Profile 2
, etc.).
3.2 Default Behavior: Dry Run and Reporting
By default, the application will:
- Scan all Chrome profiles within the User Data directory on the user’s system.
- Analyze each profile to identify the types and amounts of data (e.g., cache, cookies, history, downloads, autofill, site settings, saved passwords) that can be cleaned.
- Generate and display a detailed report for the user, listing:
- Each profile found
- The specific data types that would be cleaned per profile
- The estimated amount of disk space that would be freed by cleaning each profile and in total
- Take no destructive action (no data is erased or changed) unless the user explicitly provides a command-line flag or setting (e.g.,
--clean
or--execute
) to confirm the cleanup operation.
This dry run/reporting mode ensures users can review exactly what the tool will do and how much space will be saved before any changes are made, minimizing the risk of accidental data loss and increasing transparency.
Optional Feature:
- Allow users to export the report to a file (e.g., TXT, CSV, or HTML) for record-keeping or further review.
3.3 Optional Profile Cleanup Functionalities
The following features are optional and can be included based on project scope and user needs:
Feature | Description |
---|---|
Data Type Selection | Allow users to choose which types of data to clean for each profile (cache, cookies, history, downloads, autofill, site settings, saved passwords—with explicit warning). |
Selective or Bulk Cleanup | Enable cleaning of all profiles at once (bulk) or selected individual profiles. |
Safety Checks | Detect if Chrome is running and prompt user to close it before cleanup; offer option to back up profile data before cleaning. |
User Confirmation | Display a summary of selected actions and request user confirmation before proceeding with cleanup. |
Execution of Cleanup | Delete or securely erase selected data types from each targeted profile directory; ensure system/special profiles are excluded. |
Logging and Reporting | Log all actions taken (profiles cleaned, data types deleted, errors/skipped actions) and provide a summary report post-cleanup. |
Custom Scheduling | Allow users to schedule regular automatic cleanups (e.g., daily, weekly, monthly). |
Cross-Platform Support | Ensure all functionalities work on Windows, macOS, and Linux. |
Extensibility | Design tool to allow for future addition of new data types or support for other browsers. |
4. Non-Functional Requirements
- Cross-Platform Compatibility: Must work on Windows, macOS, and Linux.
- Performance: Should complete cleanup within a reasonable time, even with multiple profiles.
- Reliability: Must not corrupt or damage Chrome profiles.
- Usability: Easy to use for non-technical users (especially if a GUI is provided).
- Security: Must not transmit any user data externally.
5. Constraints
- The tool must be run with appropriate user permissions to access Chrome’s profile directories.
- Chrome must be closed during cleanup to avoid file access conflicts.
- Some data (like cookies or passwords) may be encrypted and not fully removable without affecting profile integrity.
6. Out of Scope
- Managing or cleaning profiles for browsers other than Google Chrome.
- Cloud-based or remote profile management.
- Enterprise-level deployment and policy management.
7. Future Enhancements (Optional)
- Scheduling automatic cleanups.
- Integration with other browsers (Edge, Chromium, etc.).
- Advanced reporting and analytics on browsing data.
8. References
End of Document
Switching to Google Gemini 2.5 Pro
Please read this requirements document and give me the best options to create / implement app or script
Analysis of Implementation Options
Based on the project requirements, here are the most viable technical approaches, ranked from most to least recommended.
1. Recommended Option: Python Script
A command-line script written in Python is the strongest choice for this project. It effectively meets all your requirements with the lowest development complexity.
Why it’s the best fit:
- Excellent Cross-Platform Support: Python runs natively on Windows, macOS, and Linux. Its standard libraries (
os
,sys
,pathlib
) make it easy to handle OS-specific differences, like file paths, in a single codebase. - Built-in Database Handling: Python includes a standard library called
sqlite3
that can directly read and modify Chrome’s database files (for history, cookies, etc.) without any external dependencies. - Rich Third-Party Libraries: Powerful, well-maintained libraries are available for key tasks:
psutil
: To safely check if the Chrome process is running.argparse
: To easily build the required command-line interface (e.g., handling the--clean
flag and other options).
- Simplicity and Readability: Python’s clean syntax makes it ideal for building and maintaining system utilities. The logic for finding profiles, calculating disk space, and deleting data will be clear and straightforward.
- Easy to Package: Tools like PyInstaller can bundle the script and its dependencies into a single executable file for easy distribution to non-technical users on any platform.
High-Level Implementation Plan (Python):
- Detect OS and Paths: Use
sys.platform
to determine the OS and define the root path to Chrome’sUser Data
directory. - Process Check: Use
psutil
to check ifchrome.exe
(orGoogle Chrome
on macOS/Linux) is running. If so, exit with a user-friendly message. - Profile Discovery: Scan the
User Data
directory for all profile folders (Default
,Profile 1
, etc.). - Dry Run & Reporting (Default Behavior):
- For each profile, connect to SQLite databases (
History
,Cookies
, etc.) usingsqlite3
. - Run
SELECT
queries to count records andos.path.getsize
to estimate the size of cache directories. - Print a formatted report to the console showing what would be deleted and the space saved.
- For each profile, connect to SQLite databases (
- Cleanup Execution (with
--clean
flag):- If the flag is present, connect to the SQLite databases and run
DELETE FROM ...
commands. - Use
shutil.rmtree
to recursively delete the contents of cache folders. - Implement a
VACUUM
command on the SQLite files to reclaim disk space after deletion.
- If the flag is present, connect to the SQLite databases and run
2. Alternative Option: Node.js Script
A Node.js script is another strong, modern alternative, especially if your development team is more comfortable with JavaScript.
Why it’s a good fit:
- Cross-Platform by Nature: Like Python, Node.js works seamlessly across Windows, macOS, and Linux.
- Powerful Package Ecosystem (NPM): High-quality packages are available for every required feature.
better-sqlite3
: A very fast and straightforward library for SQLite database interaction.yargs
orcommander
: Excellent for creating sophisticated command-line interfaces.fs-extra
: Simplifies file system operations like recursive deletion.ps-list
: For detecting running processes.
- Asynchronous Capabilities: While not essential for this project, Node.js’s async nature could efficiently handle scanning large numbers of files without blocking.
Cons vs. Python:
- Slightly less traditional for system-level scripting, but fully capable.
- Requires a packaging tool like
pkg
to create a distributable standalone executable, which is an extra step.
3. Less Suitable Options
These approaches are technically possible but come with significant drawbacks that make them a poor fit for your requirements.
- Shell Scripts (Bash for macOS/Linux, PowerShell for Windows):
- Major Drawback: Not Cross-Platform. You would need to write and maintain two completely separate scripts. This doubles the effort and introduces potential for inconsistencies.
- Poor Database Handling: Interacting with SQLite databases from a shell script is very clunky and error-prone, relying on text parsing rather than a stable API.
- Compiled Languages (Go, Rust):
- Major Drawback: Overkill. The performance benefits of a compiled language are not needed here, as the script’s speed will be limited by disk I/O, not CPU.
- Increased Complexity: Development time would be significantly longer compared to Python. The primary advantage—creating a single, dependency-free executable—is also achievable with Python and a packager.
Summary Comparison
Feature | Python (Recommended) | Node.js | Shell Scripts | Go / Rust |
---|---|---|---|---|
Cross-Platform | Excellent (Single Codebase) | Excellent (Single Codebase) | Poor (Separate Scripts) | Excellent |
Ease of Development | Excellent | Very Good | Fair | Fair to Poor |
Database Handling | Excellent (Built-in) | Excellent (via Library) | Poor (Clunky) | Good (via Library) |
Dependencies | Runtime + Libraries | Runtime + Libraries | None | None (Single Binary) |
Overall Fit | Perfect Match | Strong Alternative | Not Recommended | Overkill |
Final Recommendation:
Proceed with a Python script. It offers the most direct and efficient path to creating a reliable, maintainable, and cross-platform tool that perfectly aligns with your well-defined requirements.
OK Lets create it! make sure it is v.01 as the first revision.
Within less than 30 seconds I had this:

Excellent! Let’s get started on building the first version of your Chrome cleanup script in Python.
I will now create the initial Python script based on the high-level plan we discussed. This script will perform the core functions: detecting the OS and Chrome profiles, checking if Chrome is running, and performing a "dry run" analysis by default. It will also include the --clean and --types flags to execute the actual cleanup, just as specified in the requirements.
Chrome Profile Cleanup Script v.01
Jun 12, 7:16 PM
This script is a complete, runnable first version. It meets the core functional requirements by performing a detailed "dry run" by default and only deleting data when explicitly told to via the --clean flag.
How to Use It:
Save the code: Save the code above as a Python file, for example, chrome_cleaner.py.
Install dependencies: You'll need the psutil library. You can install it with pip:
Bash
pip install psutil
Run a Dry Run (Safe Mode): Open your terminal or command prompt, navigate to where you saved the file, and run it:
Bash
python chrome_cleaner.py
This will print a report of what it would clean without changing anything.
Run the Cleanup: To actually delete the data, use the --clean flag. You can also specify which data types to target with --types.
Bash
# Clean everything by default
python chrome_cleaner.py --clean
# Clean only cache and history
python chrome_cleaner.py --clean --types cache,history
Let me know what you think! We can now refine this, add more features, or package it for distribution.
#!/usr/bin/env python3
import argparse
import os
import pathlib
import psutil
import shutil
import sqlite3
import sys
# --- Configuration ---
# A dictionary mapping the data type names to their respective files or folders.
# This makes the script easily extensible.
DATA_TYPE_MAPPING = {
"history": {"type": "sqlite", "file": "History", "table": "urls"},
"cookies": {"type": "sqlite", "file": "Cookies", "table": "cookies"},
"downloads": {"type": "sqlite", "file": "History", "table": "downloads"},
"cache": {"type": "folder", "path": "Cache"},
"code_cache": {"type": "folder", "path": "Code Cache"},
}
DEFAULT_CLEANUP_TYPES = ["history", "cookies", "downloads", "cache", "code_cache"]
# --- Core Functions ---
def get_chrome_user_data_path():
"""
Determines the default path to the Chrome User Data directory based on the OS.
Returns:
pathlib.Path: A Path object to the User Data directory.
None: If the operating system is not supported.
"""
if sys.platform == "win32":
# Windows
return pathlib.Path(os.environ["LOCALAPPDATA"]) / "Google" / "Chrome" / "User Data"
elif sys.platform == "darwin":
# macOS
return pathlib.Path.home() / "Library" / "Application Support" / "Google" / "Chrome"
elif sys.platform == "linux":
# Linux
return pathlib.Path.home() / ".config" / "google-chrome"
else:
return None
def is_chrome_running():
"""
Checks if a Google Chrome process is currently running.
This is crucial to prevent database corruption.
Returns:
bool: True if Chrome is running, False otherwise.
"""
for proc in psutil.process_iter(['name']):
if "chrome" in proc.info['name'].lower():
return True
return False
def get_profiles(user_data_path):
"""
Finds all Chrome profile directories within the User Data directory.
Args:
user_data_path (pathlib.Path): The path to the Chrome User Data directory.
Returns:
list[pathlib.Path]: A list of Path objects for each found profile.
"""
profiles = []
if user_data_path.exists():
# The default profile is in a folder named 'Default'
default_profile = user_data_path / "Default"
if default_profile.is_dir():
profiles.append(default_profile)
# Other profiles are in folders named 'Profile 1', 'Profile 2', etc.
for item in user_data_path.iterdir():
if item.is_dir() and item.name.startswith("Profile "):
profiles.append(item)
return profiles
def get_folder_size(folder_path):
"""
Calculates the total size of a folder and all its subfolders.
Args:
folder_path (pathlib.Path): The path to the folder.
Returns:
int: The total size of the folder in bytes. Returns 0 if path doesn't exist.
"""
if not folder_path.exists():
return 0
total_size = 0
for dirpath, _, filenames in os.walk(folder_path):
for f in filenames:
fp = os.path.join(dirpath, f)
# Skip if it is a symlink
if not os.path.islink(fp):
total_size += os.path.getsize(fp)
return total_size
def format_bytes(byte_count):
"""Formats bytes into a human-readable string (KB, MB, GB)."""
if byte_count is None:
return "N/A"
power = 1024
n = 0
power_labels = {0: '', 1: 'K', 2: 'M', 3: 'G', 4: 'T'}
while byte_count >= power and n < len(power_labels):
byte_count /= power
n += 1
return f"{byte_count:.2f} {power_labels[n]}B"
def analyze_profile(profile_path, types_to_scan):
"""
Analyzes a single profile to see what data can be cleaned.
Args:
profile_path (pathlib.Path): Path to the specific profile directory.
types_to_scan (list[str]): A list of data types to analyze (e.g., ['cache', 'history']).
Returns:
dict: A dictionary containing the analysis results (e.g., {'cache': 12345, 'history': 500}).
"""
report = {}
for data_type in types_to_scan:
config = DATA_TYPE_MAPPING.get(data_type)
if not config:
continue
if config["type"] == "folder":
folder_path = profile_path / config["path"]
size = get_folder_size(folder_path)
report[data_type] = size
elif config["type"] == "sqlite":
db_path = profile_path / config["file"]
if db_path.exists():
try:
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# Check if table exists before querying
cursor.execute(f"SELECT name FROM sqlite_master WHERE type='table' AND name='{config['table']}';")
if cursor.fetchone():
cursor.execute(f"SELECT COUNT(*) FROM {config['table']}")
count = cursor.fetchone()[0]
report[data_type] = count
else:
report[data_type] = 0 # Table doesn't exist
conn.close()
except sqlite3.Error as e:
print(f" [!] Warning: Could not read {data_type} DB for {profile_path.name}: {e}")
report[data_type] = "Error"
else:
report[data_type] = 0
return report
def clean_profile(profile_path, types_to_clean):
"""
Performs the actual deletion of data for a single profile.
Args:
profile_path (pathlib.Path): Path to the specific profile directory.
types_to_clean (list[str]): A list of data types to delete.
"""
print(f"\n--- Cleaning Profile: {profile_path.name} ---")
for data_type in types_to_clean:
config = DATA_TYPE_MAPPING.get(data_type)
if not config:
print(f" [!] Skipping unknown type: {data_type}")
continue
print(f" [-] Cleaning {data_type}...", end="", flush=True)
try:
if config["type"] == "folder":
folder_path = profile_path / config["path"]
if folder_path.exists():
shutil.rmtree(folder_path)
print(" Done.")
else:
print(" Not found.")
elif config["type"] == "sqlite":
db_path = profile_path / config["file"]
if db_path.exists():
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute(f"DELETE FROM {config['table']}")
conn.commit()
# VACUUM reclaims disk space
conn.execute("VACUUM")
conn.close()
print(" Done.")
else:
print(" Not found.")
except Exception as e:
print(f" FAILED. Error: {e}")
# --- Main Execution Logic ---
def main():
"""Main function to parse arguments and orchestrate the cleanup."""
parser = argparse.ArgumentParser(
description="A script to clean browsing data from all Google Chrome profiles.",
formatter_class=argparse.RawTextHelpFormatter
)
parser.add_argument(
"--clean",
action="store_true",
help="Execute the cleanup. Without this flag, the script runs in 'dry run' mode."
)
parser.add_argument(
"--types",
type=str,
default=",".join(DEFAULT_CLEANUP_TYPES),
help="Comma-separated list of data types to clean.\n"
f"Available types: {', '.join(DATA_TYPE_MAPPING.keys())}\n"
f"Default: {','.join(DEFAULT_CLEANUP_TYPES)}"
)
args = parser.parse_args()
# --- Pre-flight Checks ---
if is_chrome_running():
print("[ERROR] Google Chrome is currently running. Please close it completely and try again.")
sys.exit(1)
user_data_path = get_chrome_user_data_path()
if not user_data_path or not user_data_path.exists():
print("[ERROR] Could not find the Google Chrome User Data directory.")
sys.exit(1)
profiles = get_profiles(user_data_path)
if not profiles:
print("[INFO] No Chrome profiles found.")
sys.exit(0)
types_to_process = [t.strip() for t in args.types.split(',')]
# --- Mode Selection: Dry Run or Clean ---
if not args.clean:
# --- Dry Run Mode (Default) ---
print("--- Chrome Cleanup Report (Dry Run) ---")
print("No data will be deleted. Run with the --clean flag to execute cleanup.")
total_report = {data_type: 0 for data_type in types_to_process}
for profile in profiles:
print(f"\n--- Analyzing Profile: {profile.name} ---")
report = analyze_profile(profile, types_to_process)
for data_type, value in report.items():
if isinstance(value, int):
config = DATA_TYPE_MAPPING[data_type]
if config['type'] == 'folder':
print(f" [+] {data_type.capitalize()}: {format_bytes(value)}")
if isinstance(total_report.get(data_type), int):
total_report[data_type] += value
else:
print(f" [+] {data_type.capitalize()} Items: {value}")
if isinstance(total_report.get(data_type), int):
total_report[data_type] += value
else: # Error case
print(f" [!] {data_type.capitalize()}: {value}")
print("\n" + "="*40)
print("--- Total Estimated Savings ---")
for data_type, value in total_report.items():
config = DATA_TYPE_MAPPING[data_type]
if config['type'] == 'folder':
print(f" [+] Total {data_type.capitalize()}: {format_bytes(value)}")
else:
print(f" [+] Total {data_type.capitalize()} Items: {value}")
print("="*40)
else:
# --- Clean Mode ---
print("!!! WARNING: You are about to permanently delete browser data. !!!")
print(f"This will affect {len(profiles)} profile(s).")
print(f"Data types to be cleaned: {', '.join(types_to_process)}")
try:
confirm = input("Type 'YES' to continue: ")
except KeyboardInterrupt:
print("\nOperation cancelled by user.")
sys.exit(0)
if confirm == "YES":
print("\nStarting cleanup...")
for profile in profiles:
clean_profile(profile, types_to_process)
print("\nCleanup complete.")
else:
print("Confirmation not received. Aborting.")
if __name__ == "__main__":
main()
So I fired up (was already opened) to my VScode and proceed to run it.

C:\Users\<user_name>\AppData\Local\Programs\Python\Python313\python.exe chrome_cleaner.py
RESULT:
--- Chrome Cleanup Report (Dry Run) ---
No data will be deleted. Run with the --clean flag to execute cleanup.
--- Analyzing Profile: Default ---
[+] History Items: 3675
[+] Cookies Items: 0
[+] Downloads Items: 2135
[+] Cache: 476.10 MB
[+] Code_cache: 306.77 MB
--- Analyzing Profile: Profile 1 ---
[+] History Items: 825
[+] Cookies Items: 0
[+] Downloads Items: 799
[+] Cache: 540.48 MB
[+] Code_cache: 382.78 MB
--- Analyzing Profile: Profile 10 ---
[+] History Items: 27
[+] Cookies Items: 0
[+] Downloads Items: 0
[+] Cache: 38.42 MB
[+] Code_cache: 981.60 KB
--- Analyzing Profile: Profile 11 ---
[+] History Items: 126
[+] Cookies Items: 0
[+] Downloads Items: 5
[+] Cache: 414.03 MB
[+] Code_cache: 284.66 MB
--- Analyzing Profile: Profile 13 ---
[+] History Items: 100
[+] Cookies Items: 0
[+] Downloads Items: 2
[+] Cache: 135.12 MB
[+] Code_cache: 76.01 MB
--- Analyzing Profile: Profile 14 ---
[+] History Items: 645
[+] Cookies Items: 0
[+] Downloads Items: 22
[+] Cache: 465.91 MB
[+] Code_cache: 297.07 MB
--- Analyzing Profile: Profile 15 ---
[+] History Items: 1022
[+] Cookies Items: 0
[+] Downloads Items: 6
[+] Cache: 401.38 MB
[+] Code_cache: 298.63 MB
--- Analyzing Profile: Profile 16 ---
[+] History Items: 247
[+] Cookies Items: 0
[+] Downloads Items: 0
[+] Cache: 355.18 MB
[+] Code_cache: 102.69 MB
--- Analyzing Profile: Profile 17 ---
[+] History Items: 41
[+] Cookies Items: 0
[+] Downloads Items: 0
[+] Cache: 44.87 MB
[+] Code_cache: 10.95 MB
--- Analyzing Profile: Profile 2 ---
[+] History Items: 53
[+] Cookies Items: 0
[+] Downloads Items: 46
[+] Cache: 570.12 MB
[+] Code_cache: 308.10 MB
--- Analyzing Profile: Profile 3 ---
[+] History Items: 43
[+] Cookies Items: 0
[+] Downloads Items: 6
[+] Cache: 369.70 MB
[+] Code_cache: 128.15 MB
--- Analyzing Profile: Profile 4 ---
[+] History Items: 1545
[+] Cookies Items: 0
[+] Downloads Items: 130
[+] Cache: 449.81 MB
[+] Code_cache: 291.46 MB
--- Analyzing Profile: Profile 5 ---
[+] History Items: 46
[+] Cookies Items: 0
[+] Downloads Items: 0
[+] Cache: 89.25 MB
[+] Code_cache: 1.27 MB
--- Analyzing Profile: Profile 6 ---
[+] History Items: 124
[+] Cookies Items: 0
[+] Downloads Items: 24
[+] Cache: 465.61 MB
[+] Code_cache: 286.24 MB
--- Analyzing Profile: Profile 7 ---
[+] History Items: 8
[+] Cookies Items: 0
[+] Downloads Items: 3
[+] Cache: 66.34 MB
[+] Code_cache: 12.40 MB
--- Analyzing Profile: Profile 8 ---
[+] History Items: 32
[+] Cookies Items: 0
[+] Downloads Items: 0
[+] Cache: 237.36 MB
[+] Code_cache: 133.73 MB
--- Analyzing Profile: Profile 9 ---
[+] History Items: 3776
[+] Cookies Items: 0
[+] Downloads Items: 94
[+] Cache: 508.46 MB
[+] Code_cache: 285.84 MB
========================================
--- Total Estimated Savings ---
[+] Total History Items: 12335
[+] Total Cookies Items: 0
[+] Total Downloads Items: 3272
[+] Total Cache: 5.50 GB
[+] Total Code_cache: 3.13 GB
========================================
PS D:\LocalData\Dev\ChromeCleaner>
TOTAL TIME FROM BEGINING to End: 15 minutes!
Before I run the script, I asked: what is code cache vs cache
That’s a great question. They both store temporary data to make your browsing faster, but they store different kinds of data for different reasons.
Here’s a simple breakdown:
Cache
(or “HTTP Cache”)
- What it stores: Web Content. This includes things like images, videos, HTML files (the structure of a page), and CSS files (the styling of a page).
- Purpose: To avoid re-downloading large files. When you visit a website, Chrome downloads the logo, pictures, and layout. It saves them in the
Cache
folder so the next time you visit that site, it can load the files directly from your hard drive instead of downloading them again from the internet. - Analogy: Think of it like a restaurant giving you a physical menu. You can look at it as many times as you want without having to ask the waiter for a new copy each time.
Code Cache
- What it stores: Compiled Code. This is specifically for JavaScript (
.js
) and WebAssembly (.wasm
) code, which makes websites interactive. - Purpose: To avoid re-processing code. When Chrome receives JavaScript, it has to parse and compile it into machine-readable instructions before it can run. This takes CPU power. The
Code Cache
stores the result of that compilation. The next time you visit, Chrome can skip the expensive compilation step and run the code immediately. - Analogy: Think of it like a pre-translated version of a foreign menu. The first time, you have to translate it word-for-word. But you save the finished translation, so on every future visit, you can just read it instantly without doing the translation work again.
In Summary:
Cache Type | Stores… | Main Goal |
---|---|---|
Cache | Images, HTML, CSS, etc. | Saves Download Time (Network) |
Code Cache | Compiled JavaScript/Wasm | Saves Processing Time (CPU) |
Export to Sheets
Both are safe to clear. Clearing them will free up disk space, but the very next time you visit a website, Chrome will simply re-download and re-compile the necessary assets, which might make the site feel a little slower on that first load.
Can you modify the script to also show the space taken by the History and Cockies Items in each profile please
#!/usr/bin/env python3
import argparse
import os
import pathlib
import psutil
import shutil
import sqlite3
import sys
# --- Configuration ---
# A dictionary mapping the data type names to their respective files or folders.
# This makes the script easily extensible.
DATA_TYPE_MAPPING = {
"history": {"type": "sqlite", "file": "History", "table": "urls"},
"cookies": {"type": "sqlite", "file": "Cookies", "table": "cookies"},
"downloads": {"type": "sqlite", "file": "History", "table": "downloads"},
"cache": {"type": "folder", "path": "Cache"},
"code_cache": {"type": "folder", "path": "Code Cache"},
}
DEFAULT_CLEANUP_TYPES = ["history", "cookies", "downloads", "cache", "code_cache"]
# --- Core Functions ---
def get_chrome_user_data_path():
"""
Determines the default path to the Chrome User Data directory based on the OS.
Returns:
pathlib.Path: A Path object to the User Data directory.
None: If the operating system is not supported.
"""
if sys.platform == "win32":
# Windows
return pathlib.Path(os.environ["LOCALAPPDATA"]) / "Google" / "Chrome" / "User Data"
elif sys.platform == "darwin":
# macOS
return pathlib.Path.home() / "Library" / "Application Support" / "Google" / "Chrome"
elif sys.platform == "linux":
# Linux
return pathlib.Path.home() / ".config" / "google-chrome"
else:
return None
def is_chrome_running():
"""
Checks if a Google Chrome process is currently running.
This is crucial to prevent database corruption.
Returns:
bool: True if Chrome is running, False otherwise.
"""
for proc in psutil.process_iter(['name']):
if "chrome" in proc.info['name'].lower():
return True
return False
def get_profiles(user_data_path):
"""
Finds all Chrome profile directories within the User Data directory.
Args:
user_data_path (pathlib.Path): The path to the Chrome User Data directory.
Returns:
list[pathlib.Path]: A list of Path objects for each found profile.
"""
profiles = []
if user_data_path.exists():
# The default profile is in a folder named 'Default'
default_profile = user_data_path / "Default"
if default_profile.is_dir():
profiles.append(default_profile)
# Other profiles are in folders named 'Profile 1', 'Profile 2', etc.
for item in user_data_path.iterdir():
if item.is_dir() and item.name.startswith("Profile "):
profiles.append(item)
return profiles
def get_folder_size(folder_path):
"""
Calculates the total size of a folder and all its subfolders.
Args:
folder_path (pathlib.Path): The path to the folder.
Returns:
int: The total size of the folder in bytes. Returns 0 if path doesn't exist.
"""
if not folder_path.exists():
return 0
total_size = 0
for dirpath, _, filenames in os.walk(folder_path):
for f in filenames:
fp = os.path.join(dirpath, f)
# Skip if it is a symlink
if not os.path.islink(fp):
total_size += os.path.getsize(fp)
return total_size
def format_bytes(byte_count):
"""Formats bytes into a human-readable string (KB, MB, GB)."""
if byte_count is None:
return "N/A"
power = 1024
n = 0
power_labels = {0: '', 1: 'K', 2: 'M', 3: 'G', 4: 'T'}
while byte_count >= power and n < len(power_labels):
byte_count /= power
n += 1
return f"{byte_count:.2f} {power_labels[n]}B"
def analyze_profile(profile_path, types_to_scan):
"""
Analyzes a single profile to see what data can be cleaned.
Args:
profile_path (pathlib.Path): Path to the specific profile directory.
types_to_scan (list[str]): A list of data types to analyze (e.g., ['cache', 'history']).
Returns:
dict: A dictionary containing the analysis results (e.g., {'cache': 12345, 'history': {'count': 500, 'size': 1024}}).
"""
report = {}
for data_type in types_to_scan:
config = DATA_TYPE_MAPPING.get(data_type)
if not config:
continue
if config["type"] == "folder":
folder_path = profile_path / config["path"]
size = get_folder_size(folder_path)
report[data_type] = size
elif config["type"] == "sqlite":
db_path = profile_path / config["file"]
if db_path.exists():
db_size = db_path.stat().st_size
try:
conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True) # Read-only connection
cursor = conn.cursor()
cursor.execute(f"SELECT name FROM sqlite_master WHERE type='table' AND name='{config['table']}';")
if cursor.fetchone():
cursor.execute(f"SELECT COUNT(*) FROM {config['table']}")
count = cursor.fetchone()[0]
report[data_type] = {"count": count, "size": db_size}
else:
report[data_type] = {"count": 0, "size": db_size} # Table doesn't exist
conn.close()
except sqlite3.Error as e:
print(f" [!] Warning: Could not read {data_type} DB for {profile_path.name}: {e}")
report[data_type] = {"count": "Error", "size": db_size}
else:
report[data_type] = {"count": 0, "size": 0}
return report
def clean_profile(profile_path, types_to_clean):
"""
Performs the actual deletion of data for a single profile.
Args:
profile_path (pathlib.Path): Path to the specific profile directory.
types_to_clean (list[str]): A list of data types to delete.
"""
print(f"\n--- Cleaning Profile: {profile_path.name} ---")
for data_type in types_to_clean:
config = DATA_TYPE_MAPPING.get(data_type)
if not config:
print(f" [!] Skipping unknown type: {data_type}")
continue
print(f" [-] Cleaning {data_type}...", end="", flush=True)
try:
if config["type"] == "folder":
folder_path = profile_path / config["path"]
if folder_path.exists():
shutil.rmtree(folder_path)
print(" Done.")
else:
print(" Not found.")
elif config["type"] == "sqlite":
db_path = profile_path / config["file"]
if db_path.exists():
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute(f"DELETE FROM {config['table']}")
conn.commit()
# VACUUM reclaims disk space
conn.execute("VACUUM")
conn.close()
print(" Done.")
else:
print(" Not found.")
except Exception as e:
print(f" FAILED. Error: {e}")
# --- Main Execution Logic ---
def main():
"""Main function to parse arguments and orchestrate the cleanup."""
parser = argparse.ArgumentParser(
description="A script to clean browsing data from all Google Chrome profiles.",
formatter_class=argparse.RawTextHelpFormatter
)
parser.add_argument(
"--clean",
action="store_true",
help="Execute the cleanup. Without this flag, the script runs in 'dry run' mode."
)
parser.add_argument(
"--types",
type=str,
default=",".join(DEFAULT_CLEANUP_TYPES),
help="Comma-separated list of data types to clean.\n"
f"Available types: {', '.join(DATA_TYPE_MAPPING.keys())}\n"
f"Default: {','.join(DEFAULT_CLEANUP_TYPES)}"
)
args = parser.parse_args()
# --- Pre-flight Checks ---
if is_chrome_running():
print("[ERROR] Google Chrome is currently running. Please close it completely and try again.")
sys.exit(1)
user_data_path = get_chrome_user_data_path()
if not user_data_path or not user_data_path.exists():
print("[ERROR] Could not find the Google Chrome User Data directory.")
sys.exit(1)
profiles = get_profiles(user_data_path)
if not profiles:
print("[INFO] No Chrome profiles found.")
sys.exit(0)
types_to_process = [t.strip() for t in args.types.split(',')]
# --- Mode Selection: Dry Run or Clean ---
if not args.clean:
# --- Dry Run Mode (Default) ---
print("--- Chrome Cleanup Report (Dry Run) ---")
print("No data will be deleted. Run with the --clean flag to execute cleanup.")
total_report = {}
for profile in profiles:
print(f"\n--- Analyzing Profile: {profile.name} ---")
report = analyze_profile(profile, types_to_process)
for data_type, value in report.items():
# Handle folders (value is an int)
if isinstance(value, int):
print(f" [+] {data_type.capitalize()}: {format_bytes(value)}")
total_report[data_type] = total_report.get(data_type, 0) + value
# Handle SQLite DBs (value is a dict)
elif isinstance(value, dict):
count = value['count']
size = value['size']
print(f" [+] {data_type.capitalize()}: {count} items ({format_bytes(size)})")
if data_type not in total_report:
total_report[data_type] = {"count": 0, "size": 0}
if isinstance(total_report[data_type].get("count"), int) and isinstance(count, int):
total_report[data_type]["count"] += count
total_report[data_type]["size"] += size
else: # Error case
print(f" [!] {data_type.capitalize()}: {value}")
print("\n" + "="*40)
print("--- Total Estimated Savings ---")
for data_type, value in total_report.items():
if isinstance(value, int):
print(f" [+] Total {data_type.capitalize()}: {format_bytes(value)}")
elif isinstance(value, dict):
print(f" [+] Total {data_type.capitalize()}: {value['count']} items ({format_bytes(value['size'])})")
print("="*40)
else:
# --- Clean Mode ---
print("!!! WARNING: You are about to permanently delete browser data. !!!")
print(f"This will affect {len(profiles)} profile(s).")
print(f"Data types to be cleaned: {', '.join(types_to_process)}")
try:
confirm = input("Type 'YES' to continue: ")
except KeyboardInterrupt:
print("\nOperation cancelled by user.")
sys.exit(0)
if confirm == "YES":
print("\nStarting cleanup...")
for profile in profiles:
clean_profile(profile, types_to_process)
print("\nCleanup complete.")
else:
print("Confirmation not received. Aborting.")
if __name__ == "__main__":
main()
RESULT
C:\Users\jorpe\AppData\Local\Programs\Python\Python313\python.exe chrome_cleaner_v0.2.py
--- Chrome Cleanup Report (Dry Run) ---
No data will be deleted. Run with the --clean flag to execute cleanup.
--- Analyzing Profile: Default ---
[+] History: 3675 items (10.84 MB)
[+] Cookies: 0 items (0.00 B)
[+] Downloads: 2135 items (10.84 MB)
[+] Cache: 476.10 MB
[+] Code_cache: 306.77 MB
--- Analyzing Profile: Profile 1 ---
[+] History: 825 items (9.94 MB)
[+] Cookies: 0 items (0.00 B)
[+] Downloads: 799 items (9.94 MB)
[+] Cache: 540.48 MB
[+] Code_cache: 382.78 MB
--- Analyzing Profile: Profile 10 ---
[+] History: 27 items (192.00 KB)
[+] Cookies: 0 items (0.00 B)
[+] Downloads: 0 items (192.00 KB)
[+] Cache: 38.42 MB
[+] Code_cache: 981.60 KB
--- Analyzing Profile: Profile 11 ---
[+] History: 126 items (768.00 KB)
[+] Cookies: 0 items (0.00 B)
[+] Downloads: 5 items (768.00 KB)
[+] Cache: 414.03 MB
[+] Code_cache: 284.66 MB
--- Analyzing Profile: Profile 13 ---
[+] History: 100 items (288.00 KB)
[+] Cookies: 0 items (0.00 B)
[+] Downloads: 2 items (288.00 KB)
[+] Cache: 135.12 MB
[+] Code_cache: 76.01 MB
--- Analyzing Profile: Profile 14 ---
[+] History: 645 items (1.34 MB)
[+] Cookies: 0 items (0.00 B)
[+] Downloads: 22 items (1.34 MB)
[+] Cache: 465.91 MB
[+] Code_cache: 297.07 MB
--- Analyzing Profile: Profile 15 ---
[+] History: 1022 items (3.12 MB)
[+] Cookies: 0 items (0.00 B)
[+] Downloads: 6 items (3.12 MB)
[+] Cache: 401.38 MB
[+] Code_cache: 298.63 MB
--- Analyzing Profile: Profile 16 ---
[+] History: 247 items (448.00 KB)
[+] Cookies: 0 items (0.00 B)
[+] Downloads: 0 items (448.00 KB)
[+] Cache: 355.18 MB
[+] Code_cache: 102.69 MB
--- Analyzing Profile: Profile 17 ---
[+] History: 41 items (240.00 KB)
[+] Cookies: 0 items (0.00 B)
[+] Downloads: 0 items (240.00 KB)
[+] Cache: 44.87 MB
[+] Code_cache: 10.95 MB
--- Analyzing Profile: Profile 2 ---
[+] History: 53 items (1.75 MB)
[+] Cookies: 0 items (0.00 B)
[+] Downloads: 46 items (1.75 MB)
[+] Cache: 570.12 MB
[+] Code_cache: 308.10 MB
--- Analyzing Profile: Profile 3 ---
[+] History: 43 items (640.00 KB)
[+] Cookies: 0 items (0.00 B)
[+] Downloads: 6 items (640.00 KB)
[+] Cache: 369.70 MB
[+] Code_cache: 128.15 MB
--- Analyzing Profile: Profile 4 ---
[+] History: 1545 items (3.88 MB)
[+] Cookies: 0 items (0.00 B)
[+] Downloads: 130 items (3.88 MB)
[+] Cache: 449.81 MB
[+] Code_cache: 291.46 MB
--- Analyzing Profile: Profile 5 ---
[+] History: 46 items (192.00 KB)
[+] Cookies: 0 items (0.00 B)
[+] Downloads: 0 items (192.00 KB)
[+] Cache: 89.25 MB
[+] Code_cache: 1.27 MB
--- Analyzing Profile: Profile 6 ---
[+] History: 124 items (2.44 MB)
[+] Cookies: 0 items (0.00 B)
[+] Downloads: 24 items (2.44 MB)
[+] Cache: 465.61 MB
[+] Code_cache: 286.24 MB
--- Analyzing Profile: Profile 7 ---
[+] History: 8 items (224.00 KB)
[+] Cookies: 0 items (0.00 B)
[+] Downloads: 3 items (224.00 KB)
[+] Cache: 66.34 MB
[+] Code_cache: 12.40 MB
--- Analyzing Profile: Profile 8 ---
[+] History: 32 items (416.00 KB)
[+] Cookies: 0 items (0.00 B)
[+] Downloads: 0 items (416.00 KB)
[+] Cache: 237.36 MB
[+] Code_cache: 133.73 MB
--- Analyzing Profile: Profile 9 ---
[+] History: 3776 items (8.81 MB)
[+] Cookies: 0 items (0.00 B)
[+] Downloads: 94 items (8.81 MB)
[+] Cache: 508.46 MB
[+] Code_cache: 285.84 MB
========================================
--- Total Estimated Savings ---
[+] Total History: 12335 items (45.45 MB)
[+] Total Cookies: 0 items (0.00 B)
[+] Total Downloads: 3272 items (45.45 MB)
[+] Total Cache: 5.50 GB
[+] Total Code_cache: 3.13 GB
========================================
So my last question: What is the command to clean the CACHE only?
Excellent question! Based on the script we created, you'll need to combine the --clean flag (to perform the deletion) with the --types flag (to specify what to delete).
To clean only the main browser cache, you would run this command:
Bash
py chrome_cleaner.py --clean --types cache
If you want to be thorough and clean both cache types (cache and code_cache), you can list them separated by a comma:
Bash
py chrome_cleaner.py --clean --types cache,code_cache
Lets run the program!
IT WORKED!
Let’s Document for publishing on GitHUb
Can you please give me something that I can please in the Readme.md file as part of the documentation. Please include:
Description, Features, Dependencies, Default behavior is informative only, Installation, Usage ( list in detail all switches, give samples) , and then license )MIT LICense
Add at the end:
Contributions
Contributions are welcome! If you’d like to contribute to the project, please fork the repository, create a feature branch, and submit a pull request.
Steps to Contribute:
Fork the repository
Create a new branch (git checkout -b feature-branch)
Commit your changes (git commit -m ‘Add new feature’)
Push to the branch (git push origin feature-branch)
Create a pull request
Author
If you have any questions or suggestions, feel free to reach out:
Jorge Pereira GitHub: @jorper98
Chrome Profile Cleanup Automation
A cross-platform Python script to analyze and clean browsing data (cache, cookies, history) from all Google Chrome profiles on a user’s computer. This tool helps improve browser performance, free up disk space, and protect privacy by automating the cleanup process.
Features
- Automatic Profile Detection: Scans for and identifies all Chrome profiles (
Default
,Profile 1
, etc.). - Cross-Platform: Fully compatible with Windows, macOS, and Linux.
- Detailed Reporting: Analyzes profiles to report on the number of items and the disk space that can be reclaimed for each data type.
- Selective Cleaning: Allows users to choose which specific data types to clean (e.g.,
cache
,history
,cookies
). - Safety First:
- Checks if Chrome is running and prompts the user to close it before making any changes.
- Requires explicit user confirmation before deleting any data.
Default Behavior: Informative Only
By default, the script runs in a “dry run” mode. It will perform a full analysis of all profiles and generate a detailed report of what would be cleaned, but it will not delete or alter any files.
Data is only deleted when the script is run with the --clean
flag and after the user provides explicit confirmation.
Dependencies
The script requires Python 3 and one external package:
psutil
: To safely check if the Chrome process is running.
Installation
- Clone the repository or download the script to your local machine.
- Install the required Python package using pip. It’s recommended to use the Python launcher
py
on Windows orpython3
on macOS/Linux to ensure the package is installed for the correct Python version.# On Windows py -m pip install psutil # On macOS / Linux python3 -m pip install psutil
Usage
All commands should be run from your terminal or command prompt in the directory where the chrome_cleaner.py
script is located.
Command-Line Switches
Switch | Argument | Description |
--clean | (No argument) | Required to delete data. Executes the cleanup process after displaying a warning and receiving user confirmation. |
--types | cache,history | (Optional) A comma-separated list of data types to clean. If not provided, it defaults to all available types. |
Available Data Types: history
, cookies
, downloads
, cache
, code_cache
Examples
1. Perform a Dry Run (Default, Safe Mode)
This command will analyze all profiles and show a report of what can be cleaned without deleting anything.
# On Windows
py chrome_cleaner.py
# On macOS / Linux
python3 chrome_cleaner.py
2. Clean ALL Default Data Types
This command will permanently delete all default data types (history
, cookies
, downloads
, cache
, and code_cache
) from every profile after you confirm.
# On Windows
py chrome_cleaner.py --clean
# On macOS / Linux
python3 chrome_cleaner.py --clean
3. Clean ONLY Cache and Code Cache
This command will permanently delete only the cache
and code_cache
folders from every profile.
# On Windows
py chrome_cleaner.py --clean --types cache,code_cache
# On macOS / Linux
python3 chrome_cleaner.py --clean --types cache,code_cache
4. Clean ONLY History
This command will permanently delete only the browsing history from every profile.
# On Windows
py chrome_cleaner.py --clean --types history
# On macOS / Linux
python3 chrome_cleaner.py --clean --types history
License
MIT License
Copyright (c) 2025 Jorge Pereira
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Contributions Are Welcome!
If you’d like to contribute to the project, please fork the repository, create a feature branch, and submit a pull request.
Steps to Contribute:
- Fork the repository
- Create a new branch (
git checkout -b feature-branch
) - Commit your changes (
git commit -m 'Add new feature'
) - Push to the branch (
git push origin feature-branch
) - Create a pull request
Author
If you have any questions or suggestions, feel free to reach out:
Jorge Pereira
- GitHub: @jorper98
- Website: https://jorgep.com
It is now 9:45p, !
GitHub Repository at: GitHub – jorper98/ChromeCleaner
Want more updates? Subscribe to my JorgeTechBits newsletter