Automate Massive Windows File Deletion with Python (Fix Long‑Path Issues)
This article demonstrates how to use Python’s built‑in functions and os.walk to automatically locate and delete specific subsystem files and folders, addresses Windows’ 256‑character path limit by prefixing paths with "\\?\", and provides complete code examples for safe bulk cleanup.
0x01 Article Background
The author’s company faces storage limits as many subsystem files (e.g., A1xxxxxx, A2xxxxx) are stored together under a single parent directory. The goal is to automatically delete historical files of selected subsystems while preserving others, which requires a programmatic solution.
0x02 Using Python to Delete Files
Python provides three core functions for deletion: os.remove() – delete a file os.rmdir() – delete an empty directory shutil.rmtree() – delete a directory and all its contents
The task is broken into four sub‑problems: identifying files, recognizing subsystem prefixes, distinguishing files from directories, and locating all target items.
os.remove("path") # delete a file
os.rmdir("path") # delete an empty folder
shutil.rmtree("path") # delete a folder treeFile identification relies on keyword matching (e.g., if keyword in filepath:), and path type is checked with os.path.isdir() and os.path.isfile(). Traversal is performed with os.walk():
import os
path = "C:\\A\\"
for root, dirs, files in os.walk(path):
print(root)
print(dirs)
print(files)0x03 Windows Long‑Path File Deletion
Windows limits user‑mode paths to 256 characters, though the API supports up to 32767 bytes. Adding the prefix \\?\ to an absolute path disables this limit. The official documentation confirms this approach.
# Get absolute path and prepend the long‑path prefix
path = "\\?\\" + os.path.abspath(path)0x04 Revised Python Script for Long Paths
import os
import shutil
path = "C:\\A\\"
keyword = "A1"
# Disable Windows path length limit
path = "\\?\\" + os.path.abspath(path)
for root, dirs, files in os.walk(path):
for dir in dirs:
if keyword in dir:
rmpath = os.path.join(root, dir)
print("删除文件夹: %s" % rmpath)
shutil.rmtree(rmpath)
for file in files:
if keyword in file:
rmpath = os.path.join(root, file)
print("删除文件: %s" % rmpath)
os.remove(rmpath)The script successfully removes both regular and ultra‑long paths, keeping the server operational.
0x05 Summary and Reflections
Key takeaways: decompose complex problems, read official documentation thoroughly, and leverage Python’s simplicity for automation tasks.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
