Computer >> Computer tutorials >  >> Programming >> Python

How to remove hidden files and folders using Python?


On Unix OS(OSX, Linux, etc) hidden files start with a '.' so we can filter them out using a simple startswith check. On windows, we need to check file attributes and then determine whether the file/folder is hidden or not.

Example

For example, you can use the following code to delete all hidden files:

import os
if os.name == 'nt':
    import win32api, win32con
def file_is_hidden(p):
    if os.name== 'nt':
        attribute = win32api.GetFileAttributes(p)
        return attribute & (win32con.FILE_ATTRIBUTE_HIDDEN | win32con.FILE_ATTRIBUTE_SYSTEM)
    else:
        return p.startswith('.') #linux-osx
[os.remove(f) for f in os.listdir('.') if file_is_hidden(f)]