Write file with specific permissions in Python

前端 未结 6 1163
一个人的身影
一个人的身影 2020-12-01 15:37

I\'m trying to create a file that is only user-readable and -writable (0600).

Is the only way to do so by using os.open() as follows?

6条回答
  •  有刺的猬
    2020-12-01 16:00

    update Folks, while I thank you for the upvotes here, I myself have to argue against my originally proposed solution below. The reason is doing things this way, there will be an amount of time, however small, where the file does exist, and does not have the proper permissions in place - this leave open wide ways of attack, and even buggy behavior.
    Of course creating the file with the correct permissions in the first place is the way to go - against the correctness of that, using Python's with is just some candy.

    So please, take this answer as an example of "what not to do";

    original post

    You can use os.chmod instead:

    >>> import os
    >>> name = "eek.txt"
    >>> with open(name, "wt") as myfile:
    ...   os.chmod(name, 0o600)
    ...   myfile.write("eeek")
    ...
    >>> os.system("ls -lh " + name)
    -rw------- 1 gwidion gwidion 4 2011-04-11 13:47 eek.txt
    0
    >>>
    

    (Note that the way to use octals in Python is by being explicit - by prefixing it with "0o" like in "0o600". In Python 2.x it would work writing just 0600 - but that is both misleading and deprecated.)

    However, if your security is critical, you probably should resort to creating it with os.open, as you do and use os.fdopen to retrieve a Python File object from the file descriptor returned by os.open.

提交回复
热议问题