Determining Whether a Directory is Writeable

前端 未结 10 1908
萌比男神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:11

    Here is something I created based on ChristopheD's answer:

    import os
    
    def isWritable(directory):
        try:
            tmp_prefix = "write_tester";
            count = 0
            filename = os.path.join(directory, tmp_prefix)
            while(os.path.exists(filename)):
                filename = "{}.{}".format(os.path.join(directory, tmp_prefix),count)
                count = count + 1
            f = open(filename,"w")
            f.close()
            os.remove(filename)
            return True
        except Exception as e:
            #print "{}".format(e)
            return False
    
    directory = "c:\\"
    if (isWritable(directory)):
        print "directory is writable"
    else:
        print "directory is not writable"
    

提交回复
热议问题