Change file to read-only mode in Python

前端 未结 4 2025
孤独总比滥情好
孤独总比滥情好 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: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)    
    

提交回复
热议问题