1

我正在尝试打开一个只读文件,从中读取并写入另一个只读文件,但出现以下错误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:

....

4

1 回答 1

1

我不完全确定您想要实现什么,如果这是最好的方法,但是,您得到的例外是:

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)

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

于 2021-06-16T08:32:21.000 回答