检查我是否可以使用 Python 将文件写入目录

发布于 2024-09-18 15:01:46 字数 106 浏览 2 评论 0原文

我需要检查是否可以使用 Python 将文件写入用户指向的目录。

有没有办法提前查一下?我可能会使用 try .. catch 来达到此目的,但我期望更好的东西,因为我可以提前检查。

I need to check if I can write a file to a directory that user point to with Python.

Is there an way to check it in advance? I may be using try .. catch for this purpose, but I expect something better in the sense that I can check in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

北斗星光 2024-09-25 15:01:46

尽管 Jim Brissom 声称,如果您预计事情失败的概率会超过百分之几,那么与“检查然后尝试”习惯用法相比,Python 中的异常处理并不便宜。 (阅读到最后以了解异常!)但是,这里的关键是您无论如何都需要检查异常,因为权限可以在检查和写入之间更改:

### !!! This is an example of what not to do!
### !!! Don't do this!
if os.access("test", os.W_OK):
    # And in here, some jerk does chmod 000 test
    open("test", "w").write(my_data)
    # Exception happens despite os.access!

os.access 和 stat 模块非常有用,如果您'例如,我们正在尝试准备一个文件夹列表,供用户选择并希望预先排除无效的文件夹。然而,当橡胶上路时,如果您希望程序健壮,它并不能替代异常处理。

现在例外是慢规则的例外:异常很慢,但磁盘更慢。如果您的磁盘负载特别重,您可能最终会在 os.access 和 open 调用之间将您感兴趣的文件从操作系统或磁盘缓存中逐出。在这种情况下,您将经历严重速度下降,因为您必须两次访问磁盘(现在,这也可能意味着网络)。

Despite Jim Brissom's claim, exception handling is not cheap in Python compared to 'check then try' idioms if you expect the thing to fail more than a few percent of the time. (Read to the end for an exception!) However, the key thing here is that you need to check the exception anyway, because the permissions can change between the check and your write:

### !!! This is an example of what not to do!
### !!! Don't do this!
if os.access("test", os.W_OK):
    # And in here, some jerk does chmod 000 test
    open("test", "w").write(my_data)
    # Exception happens despite os.access!

os.access and the stat module are great if you're trying to, e.g., prepare a list of folders for the user to pick and want to exclude invalid ones a priori. However, when the rubber hits the road, it is not a replacement for exception handling if you want your program to be robust.

And now the exception to the exceptions-are-slow rule: Exceptions are slow, but disks are slower. And if your disk is under particularly heavy load, you might end up having the file you're interested in evicted from the OS or disk cache between the os.access and open call. In this case, you're going to experience a major slowdown as you have to go to disk (and these days, that can also mean network) twice.

划一舟意中人 2024-09-25 15:01:46

您可能找不到更好或更Pythonic 的东西。 Python 的哲学是请求宽恕比请求许可更容易

如果您愿意,可以使用 os.access 。结合 os.path.isfile 检查是否你有一个文件,而不是一个目录。它可能会给你你所需要的。异常路径要好得多。

You will probably not find something better or more Pythonic. Python's philosophy is it is easier to ask forgiveness than permission.

You can use os.access if you like. Coupled with os.path.isfile to check if you have a file and not e.g. a directory. It will probably give you what you need. The exception path is much better.

薯片软お妹 2024-09-25 15:01:46

pythonic 方法是访问它并在失败时捕获异常。

如果您确实必须检查它,请使用 os.access,但结果并不总是正确,例如,请注意 Vista/Win7 中使用 UAC 的问题!

示例:

os.access(r'C:\Programme', os.R_OK)

这将告诉您是否具有读取权限。

The pythonic way is to access it and catch the exception if it fails.

If you really have to check it, use os.access, but the results are not always true, beware of issues in Vista/Win7 with UAC, for example!

Example:

os.access(r'C:\Programme', os.R_OK)

This will tell you if you have read access.

┼── 2024-09-25 15:01:46

只需使用这个:

def check_access(file, mode):
   try:
      open(file, mode)
      return True
   except PermissionError:
      return False
print(check_access("test", "w"))

如果没有权限,则输出:

False

如果权限,则输出:

True

如果您使用 os.access() ,那么您就有机会得到类似

   Traceback (most recent call last):
 File "/Users/lawrence/Library/Application Support/CodeRunner/Unsaved/Untitled.py", line 8, in <module>
   open("test", "w").write("test")
 PermissionError: [Errno 13] Permission denied: 'test'

您仍然可以使用 os.access()< 的信息/code> 但我不推荐它

just use this:

def check_access(file, mode):
   try:
      open(file, mode)
      return True
   except PermissionError:
      return False
print(check_access("test", "w"))

output if no Permission:

False

output if Permission:

True

if you use os.access() then you have a chance of getting something like

   Traceback (most recent call last):
 File "/Users/lawrence/Library/Application Support/CodeRunner/Unsaved/Untitled.py", line 8, in <module>
   open("test", "w").write("test")
 PermissionError: [Errno 13] Permission denied: 'test'

you can still use os.access() but I don't recommend it

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文