0

I am working on an idea. I need a bit help here, as I don't have in depth knowledge of python modules(I mean I don't know all the python modules). Take a look at the code

file = open('Data.txt', 'w')
a = input('Enter your name in format F|M|L: ')
file.write(a)
file.close()

The above code opens a file which writes my data to it. However I want to edit the document only through python and not through opening it from saved location. Shortly I want to disable editions done by opening the file in text-editors.

Ruturaj
  • 3
  • 4
  • You can't really do this. You could make the permissions of the file read-only, but a user with sufficient privileges could change it. I think your only real option would be to encrypt the contents, so even if the file is opened it can't be read or changed meaningfully. – Carcigenicate Aug 05 '20 at 14:08
  • Does this answer your question? [Changing file permission in Python](https://stackoverflow.com/questions/16249440/changing-file-permission-in-python) – Tomerikoo Aug 05 '20 at 14:26

2 Answers2

0

If your OS is Windows, the most straightforward option is to make the file read-only when your script is done. And set the read-only flag to false while your script is running. There are some ways to modify file permissions using pywin32 library, but it's complicated and hard to find good examples.

import os
from stat import S_IWRITE, S_IREAD

fname = 'test.txt'

# if file exists, reset read only to false (allow write)
if os.path.isfile(fname):    
    os.chmod(fname, S_IWRITE)

fid = open(fname, 'w')
fid.write('shoobie doobie')
fid.close()

It's already been pointed out in the comments, this technique won't stop a determined person from changing the read only attribute.

bfris
  • 5,272
  • 1
  • 20
  • 37
0

If text-editor is all your concern, use 'wb' instead of 'w'. Use 'rb' to open those files too.

HoD
  • 26
  • 3