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

Python批量修改.blk文件时遇PermissionError权限拒绝问题求助

解决Python批量修改.blk文件时的PermissionError权限问题

问题详情

尝试用Python批量修改大量.blk文件中的指定单词,运行参考代码时持续抛出权限错误,错误信息如下:

in WordSwap
    with open(FilePath, "w", encoding="utf-8") as file:

PermissionError: [Errno 13] Permission denied: 'C:\\Users\\user\\Documents\\First_folder\\Second_folder\\filename.blk'

使用的完整代码:

import os

def WordSwap(FolderPath):
    # Check if the provided folder exists
    if not os.path.isdir(FolderPath):
        print(f"Error: '{FolderPath}' is not a valid directory.")
        return
    
    # Loop through all files in the folder
    for filename in os.listdir(FolderPath):
        if filename.lower().endswith(".blk"):
            FilePath = os.path.join(FolderPath, filename)
            
            # Read file Contents
            with open(FilePath, "r", encoding="utf-8") as file:
                Content = file.read()
                
            # Replace all occurrences of WORD with NEWWORD
            CorrectedContent = Content.replace("WORD", "NEWWORD")
                
            # Only write if there was a change
            if CorrectedContent != Content:
                # Make a backup before overwriting
                BackupPath = FilePath + ".bak"
                with open(BackupPath, "w", encoding="utf-8") as BackupFile:
                        BackupFile.write(Content)
                        
                # Write the updated Content back to the file
                with open(FilePath, "w", encoding="utf-8") as file:
                        file.write(CorrectedContent)
                        
                print(f"Updated: {filename} (backup created: {BackupPath})")
            else:
                print(f"No 'WORD' found in: {filename}")
                    
    print("\nDone! All .blk files processed.")
    
if __name__ == "__main__":
    folder = r"C:\Users\user\Documents\First_folder\Second_folder"
    WordSwap(folder)

补充信息:

  • 脚本存放于First_folder中,使用Spyder运行
  • 已通过文件夹“属性->安全”开启完全访问权限
  • 尝试将First_folder移至C盘根目录,问题仍存在,且未生成任何备份文件

解决方案

1. 排查基础权限与占用问题

  • 关闭占用文件的程序:目标.blk文件可能被其他软件(如编辑器、关联应用)锁定,导致无法写入。关闭所有可能打开该文件的程序后重新运行脚本。
  • 以管理员身份运行Spyder:右键点击Spyder图标,选择「以管理员身份运行」,再执行脚本。即使设置了文件夹权限,非管理员进程仍可能被系统限制写入。
  • 检查文件只读属性:右键目标.blk文件→属性,取消「只读」选项的勾选。

2. 优化代码的容错与调试能力

在原代码中添加异常捕获,避免单个文件报错中断整个脚本,同时输出更详细的错误信息,方便定位问题:

import os

def WordSwap(FolderPath):
    if not os.path.isdir(FolderPath):
        print(f"Error: '{FolderPath}' is not a valid directory.")
        return
    
    for filename in os.listdir(FolderPath):
        if filename.lower().endswith(".blk"):
            FilePath = os.path.join(FolderPath, filename)
            try:
                # 读取文件
                with open(FilePath, "r", encoding="utf-8") as file:
                    Content = file.read()
                
                CorrectedContent = Content.replace("WORD", "NEWWORD")
                
                if CorrectedContent != Content:
                    BackupPath = FilePath + ".bak"
                    # 写入备份
                    try:
                        with open(BackupPath, "w", encoding="utf-8") as BackupFile:
                            BackupFile.write(Content)
                    except Exception as e:
                        print(f"Failed to create backup for {filename}: {str(e)}")
                        continue  # 跳过当前文件,继续处理下一个
                    
                    # 写入修改后的内容
                    try:
                        with open(FilePath, "w", encoding="utf-8") as file:
                            file.write(CorrectedContent)
                        print(f"Updated: {filename} (backup created: {BackupPath})")
                    except Exception as e:
                        print(f"Failed to write to {filename}: {str(e)}")
                else:
                    print(f"No 'WORD' found in: {filename}")
            except Exception as e:
                print(f"Error processing {filename}: {str(e)}")
                    
    print("\nDone! All .blk files processed.")
    
if __name__ == "__main__":
    folder = r"C:\Users\user\Documents\First_folder\Second_folder"
    WordSwap(folder)

3. 缩小范围排查

先编写一个极简脚本测试单个文件的读写,确认是否是批量处理的问题:

file_path = r"C:\Users\user\Documents\First_folder\Second_folder\test.blk"
try:
    with open(file_path, "r", encoding="utf-8") as f:
        content = f.read()
    content = content.replace("WORD", "NEWWORD")
    with open(file_path, "w", encoding="utf-8") as f:
        f.write(content)
    print("File updated successfully")
except Exception as e:
    print(f"Error: {str(e)}")

内容的提问来源于stack exchange,提问作者Ladislav Révay

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 02:23:19