You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过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.

Unix-like Systems (Linux/macOS)

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 Systems

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.

Verify It Works

After running the code, test two things:

  1. 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.
  2. Run with open("your_target_file", 'rb') as f: print(f.read())—this should successfully read the file's contents without any issues.
Key Notes
  • On Unix-like systems, if the file is owned by root, you'll need to run your Python script with sudo to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:45:41