with open() 打开文件 文件被占用 except PermissionError

    def write_yaml_data(self,value):
        """
        写入数据到yaml文件
        """
        file_path= r'./extract.yaml'
        # if not os.path.exists(file_path):
        #     os.startfile(file_path)
        try:
           with open(file_path,'a',encoding = 'utf-8') as f:

                if isinstance(value,dict):
                    write_data = yaml.dump(value,allow_unicode = True, sort_keys=False)
                    f.write(write_data)
                else:
                    print('写入失败: 写入到extract必须为字典类型')

        except PermissionError:
            print(f"错误:文件{file_path}正被其他程序占用,请先关闭该文件")

        except Exception as e:
            print(e)

 

posted @ 2026-05-10 17:31  Avicii_2018  阅读(6)  评论(0)    收藏  举报