如何通过Python将文件设为不可执行并保留读取权限?
Got it, let's walk through how to do this properly—since file permissions work a bit differently across Unix-like systems (Linux, macOS) and Windows, I'll cover both cases to make sure you're covered no matter what OS you're on.
On these systems, file permissions are based on three sets of bits: read (r), write (w), execute (x) for the file owner, group, and other users respectively. To make a file non-executable while keeping it readable, we just need to strip the execute bits for all users, while leaving the read bits intact.
You can do this using either the built-in os module or the more modern pathlib module:
Using os module
import os file_path = "your_target_file" # Get the current permission mode of the file current_mode = os.stat(file_path).st_mode # Strip execute bits for all users (0o111 is the octal mask for execute permissions) new_mode = current_mode & ~0o111 # Apply the new permissions os.chmod(file_path, new_mode)
Using pathlib (Python 3.4+)
If you prefer object-oriented file handling, pathlib is cleaner:
from pathlib import Path file = Path("your_target_file") current_mode = file.stat().st_mode new_mode = current_mode & ~0o111 file.chmod(new_mode)
What's happening here? The ~0o111 flips all the bits of the execute mask, so when we do a bitwise AND with the current mode, we clear only the execute bits—leaving read (and write, if it existed) permissions untouched. This ensures you can still open the file with open("your_target_file", 'rb') without issues.
Windows uses a more complex ACL (Access Control List) system instead of Unix-style permission bits, so the approach is a bit different. The key is to explicitly allow read access while denying execute permissions.
First, you'll need the pywin32 package (install it with pip install pywin32):
import win32security import win32api import win32con file_path = "your_target_file" # Get the file's existing security descriptor sd = win32security.GetFileSecurity(file_path, win32security.DACL_SECURITY_INFORMATION) dacl = sd.GetSecurityDescriptorDacl() # Get the SID (Security Identifier) for the current user current_username = win32api.GetUserName() user_sid = win32security.LookupAccountName(None, current_username)[0] # Allow read permissions (read data and file attributes) dacl.AddAccessAllowedAce(win32security.ACL_REVISION, win32con.FILE_READ_DATA | win32con.FILE_READ_ATTRIBUTES, user_sid) # Deny execute permissions dacl.AddAccessDeniedAce(win32security.ACL_REVISION, win32con.FILE_EXECUTE, user_sid) # Apply the updated security descriptor back to the file sd.SetSecurityDescriptorDacl(1, dacl, 0) win32security.SetFileSecurity(file_path, win32security.DACL_SECURITY_INFORMATION, sd)
Note: For system-wide files or files owned by other users, you might need to run your Python script as an administrator to modify permissions.
After running the code, test two things:
- Try executing the file (on Unix, run
./your_target_file; on Windows, double-click it or run it via Command Prompt). You should get a permission error. - Run
with open("your_target_file", 'rb') as f: print(f.read())—this should successfully read the file's contents without any issues.
- On Unix-like systems, if the file is owned by root, you'll need to run your Python script with
sudoto modify permissions. - For Windows, if you're dealing with non-executable file types (like
.txt), they're already not executable by default—but this code ensures even executable types (like.exe) can't be run while still being readable.
内容的提问来源于stack exchange,提问作者pfffffffff

