【问题标题】:Write in a read-only file写入只读文件
【发布时间】:2021-09-01 01:09:23
【问题描述】:

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

....

【问题讨论】:

  • 您正在尝试打开os.chmod 的输出,而不是实际文件
  • 当我尝试直接打开文件时,我得到 PermissionError : Permission denied: file 这就是我使用 os.chmod 的原因

标签: python python-3.x python-2.7 readonly readonly-attribute


【解决方案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)

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

【讨论】:

  • def delete_line_by_string(original_file, line_to_delete) 987654327 copy_file= original_file 987654329 for line in read_obj: 987654331 if line[-1] == '\n': 987654333 if( line_to_delete in line_to_match) == False: 987654335 else: 987654337 if is_skipped: 987654339 @ os.rename(copy_file, original_file)else:os.remove(copy_file)
  • 谢谢我真正想做的是根据一个字符串删除一行,所以如果在这个文件的行中找到一个字符串,它应该被删除/删除。但是该文件是只读的,所以我要么得到 Permission denied 要么得到 TypeError: ...,not Nonetype 。在我的情况下,我的代码看起来像上面写的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-14
  • 2012-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-16
相关资源
最近更新 更多