1

I am trying to open a read only file, read from it and write in in another read-only file but I get the following error TypeError: excepted str, bytes or Os.Pathlike object, not NoneType My code goes like : 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:

....

1 Answers1

1

I am not entirely sure what you want to achieve and if that is the best way, however, the exception you are getting:

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

is because you are trying to open output of os.chmod, which has no return value, if you want to chmod a file to be able to write to it and then make it read-only again, you can do something like this:

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)

Bear in mind that this snippet will allow racing the file writeability, as there is a small period in which the file is writeable (race condition) - impact of this "feature" depends on your use case.

Josef Korbel
  • 1,168
  • 1
  • 9
  • 32
  • `def delete_line_by_string(original_file, line_to_delete)` `is_skipped = False` `copy_file= original_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:` `for line in read_obj:` `line_to_match= line` `if line[-1] == '\n':` `line_to_match= line [:-1]` `if( line_to_delete in line_to_match) == False:` `write_obj.write(line)` `else:` `is_skipped= True` `if is_skipped:` `os.remove(original_file)` `os.rename(copy_file, original_file)` `else:` `os.remove(copy_file)` – user14635293 Jun 16 '21 at 18:20
  • Thanks what I actually wanted to do is delete a line according to a string, so if a string is found in the line of this file it should be deleted/removed. But the file is a read only so I either get `Permission denied` or `TypeError: ...,not Nonetype` .In my case my code looks like written above – user14635293 Jun 16 '21 at 18:24