python 打开文件报错,[Errno 9] Bad file descriptor

今天在开发中修改代码漏洞,漏洞提示打开文件需要指定权限。我修改了下面代码,编译时候报了错。:
修改前:

            with open(self.SPCFG_PATH, "w") as file_object:
                json.dump(spcfg_json, file_object, indent=1)

修改后:

            flags = os.O_WRONLY | os.O_RDWR | os.O_CREAT
            modes = stat.S_IRWXU
            with os.fdopen(os.open(self.SPCFG_PATH, flags, modes), 'w') as file_object:

改成上面这样编译报错,Bad file descriptor。猜想也就是权限冲突问题。最终改成下面这行代码成功了。

            flags = os.O_RDWR | os.O_CREAT
            modes = stat.S_IWUSR | stat.S_IRUSR
            with os.fdopen(os.open(self.SPCFG_PATH, flags, modes), 'w+') as file_object:
                json.dump(spcfg_json, file_object, indent=1)

'w’和’w+'的区别:
w : 打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。
w+ : 打开一个文件用于读写。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。

不太明白为什么会权限冲突,先记录下,以后有时间再研究下。

Guess you like

Origin blog.csdn.net/weixin_42648692/article/details/125868193