ill*_*ger 93 python directory permissions operating-system file
Python中确定目录对于执行脚本的用户是否可写的最佳方法是什么?由于这可能涉及使用os模块,我应该提到我在*nix环境下运行它.
Max*_*keh 162
虽然Christophe建议的是更Pythonic解决方案,但os模块确实具有os.access函数来检查访问:
os.access('/path/to/folder', os.W_OK) #W_OK用于写入,R_OK用于阅读等.
Chr*_*heD 67
建议这可能看起来很奇怪,但一个常见的Python习语是
要求宽恕比获得许可更容易
在这个成语之后,有人会说:
尝试写入相关目录,如果您没有权限,请捕获错误.
zak*_*zak 18
我使用该tempfile模块的解决方案:
import tempfile
import errno
def isWritable(path):
try:
testfile = tempfile.TemporaryFile(dir = path)
testfile.close()
except OSError as e:
if e.errno == errno.EACCES: # 13
return False
e.filename = path
raise
return True
Run Code Online (Sandbox Code Playgroud)
Roh*_*haq 10
偶然发现这个线程正在寻找某人的例子.对谷歌的第一个结果,恭喜!
人们在这个帖子中谈论Pythonic的做法,但没有简单的代码示例?在这里,对于其他任何偶然发现的人:
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")
Run Code Online (Sandbox Code Playgroud)
这会尝试打开文件句柄进行写入,如果指定的文件无法写入,则会以错误退出:这更容易阅读,并且是一种更好的方法,而不是在文件路径或目录上进行预先检查,因为它避免了竞争条件; 在运行预检和实际尝试写入文件之间文件变为不可写的情况.
检查模式位:
def isWritable(name):
uid = os.geteuid()
gid = os.getegid()
s = os.stat(dirname)
mode = s[stat.ST_MODE]
return (
((s[stat.ST_UID] == uid) and (mode & stat.S_IWUSR)) or
((s[stat.ST_GID] == gid) and (mode & stat.S_IWGRP)) or
(mode & stat.S_IWOTH)
)
Run Code Online (Sandbox Code Playgroud)
这是我根据 ChristopheD 的回答创建的内容:
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"
Run Code Online (Sandbox Code Playgroud)