Free Up Your Disk Space in 5 Minutes: A Quick Python iCloud Guide
Tags: python, programming, tutorial
Published: 2023-04-18 20:35:42


I’ve had my iCloud 2TB subscription for a couple months now and while working on some personal backups I got a "not enough disk space" message that got me confused. I went and checked my iCloud configuration and noticed this message:

![optmize storage option](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/96ee4ypg52zibwbrg2iy.png)

So I went and checked my iCloud disk space and saw that in fact, most of my files were stored both in disk and iCloud!


![icloud disk space](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0fxld7rjmqjfwryvvvsp.png)

I also noticed that you could have folders as "uploaded and not local" but files with local copies within the same folder.

![icloud file details](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2soc9phwgt55bdg5v12f.png)

Enough introduction, let's fix this!

---

### Step 1: Import libraries and define our functions:
```python
import os
import subprocess

def get_file_paths(directory):
    file_paths = []
    
    for foldername, subfolders, filenames in os.walk(directory):
        for filename in filenames:
            file_path = os.path.join(foldername, filename)
            file_paths.append(file_path)
    return file_paths

def format_size(size):
    if size >= 1e9:
        return f"{size/1e9:.2f}GB"
    elif size >= 1e6:
        return f"{size/1e6:.2f}MB"
    elif size >= 1e3:
        return f"{size/1e3:.2f}KB"
    else:
        return f"{size}B"
```

_**get_file_paths(directory)**_ returns a list of file paths for all files in the directory and its subdirectories.

_**format_size(size)**_ formats a given size in bytes into a readable string and appropriate unit (B, KB, MB, or GB).

Luckily for us, on _macOS Ventura 13.2.1_ iCloud files that do not have a local copy, get a ".icloud" attached to the end of it's file path. So we can ignore those files and some others we might not want to remove.

```python
directory = 'path/to/your/directory/'
ignore_files = ['.DS_Store', '.icloud']

if __name__ == "__main__":
    file_paths = get_file_paths(directory)

    removed_count = 0
    total_freed_size = 0

    for file_path in file_paths:
        if file_path.endswith(tuple(ignore_files)):
                continue
        elif os.path.isfile(file_path):
            try:
                result = subprocess.run(["brctl", "evict", file_path], capture_output=True, check=True)
                removed_count += 1
                freed_size = os.path.getsize(file_path)
                total_freed_size += freed_size
                print(f"Local copy removed for: {file_path}") #comment out if you don't want to list every file action
            except subprocess.CalledProcessError as e:
                print(f"Error in removing the local copy of the file: {file_path}")
                print(e)
            except Exception as e:
                print(e)

    print(f"\nLocal Copies Removed: {removed_count}\nFree Disk Space: {format_size(total_freed_size)}")
```

The main code starts the process and removes only the local copy for each file.

> tip: You can comment out the action by file and just get the final message with how many files were removed and the space freed up.

Now just sit back, relax and enjoy your SSD new space!


![code running](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3fjv7mdagim0c77locfq.png)

Let me know your thoughts about it, comment below if you would like me to explore other storage options like Google Drive, Box…

---

###### Thanks for reading, consider subscribing!