我不完全确定您想要实现什么,如果这是最好的方法,但是,您得到的例外是:
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)
请记住,此代码段将允许对文件的可写性进行竞赛,因为文件可写的时间很短(竞争条件)-此“功能”的影响取决于您的用例。