写入只读文件

2024-05-19 09:48:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图打开一个只读文件,从中读取并写入另一个只读文件,但出现以下错误TypeError: excepted str, bytes or Os.Pathlike object, not NoneType 我的代码如下: copy_file=file

with open(os.chmod( file, stat.S_IREAD), ‘r’) as read_obj, open(os.chmod(copy_file, stat.S_IWRITE), ‘w’) as write_obj:

....


Tags: or文件objbytesosas错误open
1条回答
网友
1楼 · 发布于 2024-05-19 09:48:18

我不完全确定你想要实现什么,如果这是最好的方式,但是,你会得到一个例外:

TypeError: excepted str, bytes or Os.Pathlike object, not NoneType

是因为您正在尝试open输出os.chmod,该输出没有返回值,如果您希望chmod一个文件能够写入,然后再次将其设为只读,则可以执行以下操作:

import os
import stat

read_only_file = "1.txt"
read_write_file = "2.txt"

def make_read_only(filename: str) -> None:
    os.chmod(filename, stat.S_IREAD)

def make_read_write(filename: str) -> None:
    os.chmod(filename, stat.S_IWRITE)

# Read read only file
with open(read_only_file) as f:
    data = f.read()

make_read_write(read_write_file)
with open(read_write_file, "w") as f:
    f.write(data)
make_read_only(read_write_file)

请记住,此代码段将允许对文件的可写性进行竞争,因为文件在很短的时间内是可写的(竞争条件)——此“功能”的影响取决于您的用例

相关问题 更多 >

    热门问题