tempfile模块报错:PermissionError: [Errno 13] Permission denied的解决方法

发布时间:2024年01月11日

?最近在win11上运行了个linux上的代码。出现报错:

Traceback (most recent call last):
  File "test.py", line 65, in <module>
    logger, cfg = init()
  File "test.py", line 51, in init
    cfg = gorilla.Config.fromfile(args.config)
  File "C:\Users\user\.conda\envs\DPDN\lib\site-packages\gorilla\config\config.py", line 224, in fromfile
    use_predefined_variables)
  File "C:\Users\user\.conda\envs\DPDN\lib\site-packages\gorilla\config\config.py", line 140, in _file2dict
    temp_config_file.name)
  File "C:\Users\user\.conda\envs\DPDN\lib\site-packages\gorilla\config\config.py", line 116, in _substitute_predefined_vars
    with open(temp_config_name, "w") as tmp_config_file:
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\user\\AppData\\Local\\Temp\\tmplp2w2mnr\\tmp3m46e8tx.yaml'

这是因为在linux系统里不关闭文件即可再次打开读取内容,但是在windows系统,不关闭就没有权限再次打开,C:\Users\user\.conda\envs\DPDN\lib\site-packages\gorilla\config\config.py中的_file2dict()函数想在C盘创建临时文件,但是PyTorch没有在C盘创建文件的权限,因此造成了PermissionError.解决的办法是在D盘创建一个Temp文件夹,让_file2dict()在D盘创建临时文件,就不会有PermissionError了.因此对_file2dict(filename, use_predefined_variables=True)这个函数进行了修改,此处借鉴

?把源代码

    @staticmethod
    def _file2dict(filename: str, use_predefined_variables: bool=True):
        filename = osp.abspath(osp.expanduser(filename))
        check_file(filename)
        file_extname = osp.splitext(filename)[1]
        if file_extname not in [".py", ".json", ".yaml", ".yml"]:
            raise IOError("Only py/yml/yaml/json type are supported now!")

        with tempfile.TemporaryDirectory() as temp_config_dir:
            temp_config_file = tempfile.NamedTemporaryFile(dir=temp_config_dir,
                                                           suffix=file_extname)

            temp_config_name = osp.basename(temp_config_file.name)
            # Substitute predefined variables
            if use_predefined_variables:
                Config._substitute_predefined_vars(filename,
                                                   temp_config_file.name)
            else:
                shutil.copyfile(filename, temp_config_file.name)

替换成

@staticmethod
    def _file2dict(filename, use_predefined_variables=True):
        filename = osp.abspath(osp.expanduser(filename))
        filenames = filename.split('\\')
        if filenames[0] == 'C:':
            filename = 'D:\\Temp\\' +filenames[-1]
            f = open(filename, 'w')
            f.close()
        check_file(filename)
        fileExtname = osp.splitext(filename)[1]
        if fileExtname not in ['.py', '.json', '.yaml', '.yml']:
            raise IOError('Only py/yml/yaml/json type are supported now!')

        with tempfile.TemporaryDirectory() as temp_config_dir:
            temp_config_dir = 'D:\\Temp\\' + temp_config_dir.split('\\')[-1]
            os.makedirs(temp_config_dir)
            temp_config_file = tempfile.NamedTemporaryFile(
                dir=temp_config_dir, suffix=fileExtname)
            if platform.system() == 'Windows':
                temp_config_file.close()
            temp_config_name = osp.basename(temp_config_file.name)
            # Substitute predefined variables
            if use_predefined_variables:
                Config._substitute_predefined_vars(filename,
                                                   temp_config_file.name)
            else:
                shutil.copyfile(filename, temp_config_file.name)

然后在头部导入:

import os

import?platform

完美解决?

文章来源:https://blog.csdn.net/weixin_43693391/article/details/135504812
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。