Change file to read-only mode in Python

前端 未结 4 2005
孤独总比滥情好
孤独总比滥情好 2020-12-06 05:13

I am writing a data processing code, in which I create a new file, write processed data in to this file and close. But the file has to be closed in read-only mode, so that i

相关标签:
4条回答
  • 2020-12-06 05:30

    I guess you could use os module after writing on your file to change the file permissions like this:

    import os
    filename=open("file_name","w")
    filename.write("my text")
    filename.close()
    os.system("chmod 444 file_name")
    
    0 讨论(0)
  • 2020-12-06 05:37

    For this you use os.chmod

    import os
    from stat import S_IREAD, S_IRGRP, S_IROTH
    
    filename = "path/to/file"
    os.chmod(filename, S_IREAD|S_IRGRP|S_IROTH)
    

    Note that this assumes you have appropriate permissions, and that you want more than just the owner to be able to read the file. Remove S_IROTH and S_IRGRP as appropriate if that's not the case.

    UPDATE

    If you need to make the file writable again, simply call os.chmod as so:

    from stat import S_IWUSR # Need to add this import to the ones above
    
    os.chmod(filename, S_IWUSR|S_IREAD) # This makes the file read/write for the owner
    

    Simply call this before you open the file for writing, then call the first form to make it read-only again after you're done.

    0 讨论(0)
  • 2020-12-06 05:38

    This solution preserves previous permission of the file, acting like command chmod -w FILE

    import os
    import stat
    
    filename = "path/to/file"
    mode = os.stat(filename).st_mode
    ro_mask = 0777 ^ (stat.S_IWRITE | stat.S_IWGRP | stat.S_IWOTH)
    os.chmod(filename, mode & ro_mask)    
    
    0 讨论(0)
  • 2020-12-06 05:45

    For Windows OS maybe to try something like this:

    import os
    
    filename = open("file_name.txt", "w")
    filename.write("my text")
    filename.close()
    os.system("attrib +r file_name.txt")
    
    0 讨论(0)
提交回复
热议问题