如何用Python在Windows系统中隐藏与显示指定文件或文件夹
Hey there! Let's tackle your two Python-on-Windows file/folder hiding questions—super common use cases, and I've got straightforward, reliable solutions for you.
There are two solid approaches here: using Windows' native API via ctypes (most robust, no external dependencies) or leveraging the command-line attrib tool via subprocess. Let's break both down.
Method 1: Use ctypes to Call Windows API
This directly interacts with Windows' kernel functions, so it's fast and doesn't rely on shell commands.
Hide a File/Folder
import ctypes from ctypes import wintypes # Define Windows API functions we need GetFileAttributes = ctypes.windll.kernel32.GetFileAttributesW SetFileAttributes = ctypes.windll.kernel32.SetFileAttributesW FILE_ATTRIBUTE_HIDDEN = 0x02 FILE_ATTRIBUTE_NORMAL = 0x80 def hide_item(path): # Get current file/folder attributes attrs = GetFileAttributes(path) if attrs == -1: raise FileNotFoundError(f"Path not found: {path}") # Add hidden attribute if not already present if not (attrs & FILE_ATTRIBUTE_HIDDEN): SetFileAttributes(path, attrs | FILE_ATTRIBUTE_HIDDEN) print(f"Successfully hidden: {path}") else: print(f"Item is already hidden: {path}") # Example usage hide_item(r"C:\Users\YourName\Documents\secret_project") hide_item(r"C:\Users\YourName\Desktop\private_note.txt")
Show a Hidden File/Folder
def show_item(path): attrs = GetFileAttributes(path) if attrs == -1: raise FileNotFoundError(f"Path not found: {path}") # Remove hidden attribute while keeping other attributes intact if attrs & FILE_ATTRIBUTE_HIDDEN: SetFileAttributes(path, attrs & ~FILE_ATTRIBUTE_HIDDEN) print(f"Successfully unhidden: {path}") else: print(f"Item is already visible: {path}") # Example usage show_item(r"C:\Users\YourName\Documents\secret_project")
Method 2: Use subprocess with attrib Command
This uses Windows' built-in attrib command, which is simpler to write but relies on the system shell.
Hide a File/Folder
import subprocess def hide_item_attrib(path): # +h adds hidden attribute; /s applies to subitems if it's a folder subprocess.run(["attrib", "+h", path, "/s"], check=True, shell=True) print(f"Hidden via attrib: {path}") # Example hide_item_attrib(r"C:\Users\YourName\Downloads\confidential.zip")
Show a Hidden File/Folder
def show_item_attrib(path): # -h removes hidden attribute subprocess.run(["attrib", "-h", path, "/s"], check=True, shell=True) print(f"Unhidden via attrib: {path}")
First, let's clarify what "opening" means here—whether you're launching the folder in File Explorer, opening a file in its default app, or just holding a file handle in Python.
Case A: You opened the item in File Explorer/default app (e.g., with os.startfile)
If you used os.startfile(path) to launch the folder/file, you can call the hide function we wrote right after. Windows allows modifying the hidden attribute even if the item is open in File Explorer:
import os import time # Open the folder in File Explorer os.startfile(r"C:\Users\YourName\Documents\temp_workspace") # Optional: Wait a second to let Explorer fully open the item time.sleep(1) # Hide the folder immediately after hide_item(r"C:\Users\YourName\Documents\temp_workspace")
Case B: You opened a file handle in Python (e.g., with open())
If you have an active file handle (like f = open("private.txt", "r")), Windows might block you from modifying the file's attributes while it's in use. The workaround is to close the file first, then hide it, or hide it before opening if that fits your workflow:
# Option 1: Close the file first, then hide f = open(r"C:\Users\YourName\Desktop\meeting_notes.txt", "r") # Do your reading/writing here content = f.read() f.close() # Now hide the file hide_item(r"C:\Users\YourName\Desktop\meeting_notes.txt") # Option 2: Hide first, then open (if you don't need it visible before access) hide_item(r"C:\Users\YourName\Desktop\meeting_notes.txt") with open(r"C:\Users\YourName\Desktop\meeting_notes.txt", "r") as f: content = f.read() # The file stays hidden even while open in Python
A quick heads-up: If you're trying to hide a file while it's open in a third-party app (like Microsoft Word), that app might lock the file, and you'll get an error when trying to modify attributes. In that case, you'll need to close the app first or wait for it to release the file lock.
内容的提问来源于stack exchange,提问作者Nick_2440

