Determining Whether a Directory is Writeable

前端 未结 10 1916
萌比男神i
萌比男神i 2020-12-07 14:44

What would be the best way in Python to determine whether a directory is writeable for the user executing the script? Since this will likely involve using the os module I sh

10条回答
  •  庸人自扰
    2020-12-07 15:06

    Stumbled across this thread searching for examples for someone. First result on Google, congrats!

    People talk about the Pythonic way of doing it in this thread, but no simple code examples? Here you go, for anyone else who stumbles in:

    import sys
    
    filepath = 'C:\\path\\to\\your\\file.txt'
    
    try:
        filehandle = open( filepath, 'w' )
    except IOError:
        sys.exit( 'Unable to write to file ' + filepath )
    
    filehandle.write("I am writing this text to the file\n")
    

    This attempts to open a filehandle for writing, and exits with an error if the file specified cannot be written to: This is far easier to read, and is a much better way of doing it rather than doing prechecks on the file path or the directory, as it avoids race conditions; cases where the file becomes unwriteable between the time you run the precheck, and when you actually attempt to write to the file.

提交回复
热议问题