- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个路径(包括目录和文件名)。
我需要测试文件名是否有效,例如如果文件系统允许我创建一个具有这样名称的文件。
文件名中包含一些 unicode 字符。
可以安全地假设路径的目录段是有效且可访问的(我试图使问题更适用,显然我太过分了)。
除非万不得已,否则我非常不想逃避任何事情。
我会发布一些我正在处理的示例字符,但显然它们会被堆栈交换系统自动删除。无论如何,我想保留标准的 unicode 实体,如 ö
, 并且只转义文件名中无效的内容。
这是问题所在。 路径的目标处可能(或可能没有)已经有一个文件。 如果该文件确实存在,我需要保留该文件,如果不存在则不创建文件。
基本上我想检查是否可以写入路径 没有实际打开写入路径 (以及通常需要的自动文件创建/文件破坏)。
因此:
try:
open(filename, 'w')
except OSError:
# handle error here
if not os.access(filePath, os.W_OK):
try:
open(filePath, 'w').close()
os.unlink(filePath)
except OSError:
# handle error here
filePath
处创建文件,然后我将不得不
os.unlink
.
os.isvalidpath(filePath)
那样简单的事情似乎要花 6 或 7 行代码才能完成。或类似。
最佳答案
tl;博士
拨打 is_path_exists_or_creatable()
函数定义如下。
严格来说是 Python 3。这就是我们滚动的方式。
两个问题的故事
“我如何测试路径名有效性,以及对于有效路径名,这些路径的存在或可写性”的问题?显然是两个不同的问题。两者都很有趣,而且都没有在这里得到真正令人满意的答案......或者,在我可以 grep 的任何地方。
vikki的 answer可能是最接近的,但具有以下显着缺点:
/
)。 %HOMEDRIVE%
,包含当前 Windows 安装的冒号后缀驱动器号(通常但不一定是 C:
)。 ext4
(以及大多数但不是所有 POSIX 兼容的)文件系统,当且仅当该路径名在语法上是正确的:
\x00
)。这是所有 POSIX 兼容文件系统的硬性要求。 'a'*256
)。路径组件是路径名的最长子串,不包含 /
字符(例如, bergtatt
、 ind
、 i
和 fjeldkamrene
在路径名 /bergtatt/ind/i/fjeldkamrene
中)。 os.path
包应该为此提供开箱即用的解决方案。由于未知(并且可能没有说服力)的原因,它没有。幸运的是,展开您自己的临时解决方案并不是那么令人痛苦……
os.stat()
和
os.lstat()
传递无效路径名时,函数会引发以下异常:
FileNotFoundError
的实例. WindowsError
的实例谁的winerror
属性是 123
(即, ERROR_INVALID_NAME
)。 '\x00'
), TypeError
的实例. OSError
的实例谁的errcode
属性是:errno.ERANGE
. (这似乎是操作系统级别的错误,也称为 POSIX 标准的“选择性解释”。)errno.ENAMETOOLONG
. os.stat()
和
os.lstat()
函数引发泛型
FileNotFoundError
传递的路径名驻留在不存在的目录中时的异常,无论这些路径名是否无效。目录存在优先于路径名无效。
ext4
上语法正确的路径名。文件系统不包含路径组件
(A) 包含空字节或
(B) 长度超过 255 个字节。因此,一个
ext4
当且仅当该路径名中的所有路径组件都有效时,路径名才有效。大多数情况都是如此
real-world filesystems出于兴趣。
/troldskog/faren/vild
到列表 ['', 'troldskog', 'faren', 'vild']
中)。 /troldskog
)。 os.stat()
或 os.lstat()
.如果该路径名以及该组件无效,则此调用保证会引发异常,从而暴露无效类型而不是通用 FileNotFoundError
异常(exception)。为什么? 因为该路径名驻留在现有目录中。 (循环逻辑是循环的。)os.stat()
或
os.lstat()
邀请竞争条件,即使该目录先前已被测试存在。为什么?因为在执行该测试之后但在将该路径名传递给
os.stat()
之前,无法阻止外部进程同时删除该目录。或
os.lstat()
.释放精神错乱的狗!
Front-facing applications validating arbitrary pathnames from untrusted sources by simply passing such pathnames to
os.stat()
oros.lstat()
are susceptible to Denial of Service (DoS) attacks and other black-hat shenanigans. Malicious users may attempt to repeatedly validate pathnames residing on filesystems known to be stale or otherwise slow (e.g., NFS Samba shares); in that case, blindly statting incoming pathnames is liable to either eventually fail with connection timeouts or consume more time and resources than your feeble capacity to withstand unemployment.
import errno, os
# Sadly, Python fails to provide the following magic number for us.
ERROR_INVALID_NAME = 123
'''
Windows-specific error code indicating an invalid pathname.
See Also
----------
https://docs.microsoft.com/en-us/windows/win32/debug/system-error-codes--0-499-
Official listing of all such codes.
'''
def is_pathname_valid(pathname: str) -> bool:
'''
`True` if the passed pathname is a valid pathname for the current OS;
`False` otherwise.
'''
# If this pathname is either not a string or is but is empty, this pathname
# is invalid.
try:
if not isinstance(pathname, str) or not pathname:
return False
# Strip this pathname's Windows-specific drive specifier (e.g., `C:\`)
# if any. Since Windows prohibits path components from containing `:`
# characters, failing to strip this `:`-suffixed prefix would
# erroneously invalidate all valid absolute Windows pathnames.
_, pathname = os.path.splitdrive(pathname)
# Directory guaranteed to exist. If the current OS is Windows, this is
# the drive to which Windows was installed (e.g., the "%HOMEDRIVE%"
# environment variable); else, the typical root directory.
root_dirname = os.environ.get('HOMEDRIVE', 'C:') \
if sys.platform == 'win32' else os.path.sep
assert os.path.isdir(root_dirname) # ...Murphy and her ironclad Law
# Append a path separator to this directory if needed.
root_dirname = root_dirname.rstrip(os.path.sep) + os.path.sep
# Test whether each path component split from this pathname is valid or
# not, ignoring non-existent and non-readable path components.
for pathname_part in pathname.split(os.path.sep):
try:
os.lstat(root_dirname + pathname_part)
# If an OS-specific exception is raised, its error code
# indicates whether this pathname is valid or not. Unless this
# is the case, this exception implies an ignorable kernel or
# filesystem complaint (e.g., path not found or inaccessible).
#
# Only the following exceptions indicate invalid pathnames:
#
# * Instances of the Windows-specific "WindowsError" class
# defining the "winerror" attribute whose value is
# "ERROR_INVALID_NAME". Under Windows, "winerror" is more
# fine-grained and hence useful than the generic "errno"
# attribute. When a too-long pathname is passed, for example,
# "errno" is "ENOENT" (i.e., no such file or directory) rather
# than "ENAMETOOLONG" (i.e., file name too long).
# * Instances of the cross-platform "OSError" class defining the
# generic "errno" attribute whose value is either:
# * Under most POSIX-compatible OSes, "ENAMETOOLONG".
# * Under some edge-case OSes (e.g., SunOS, *BSD), "ERANGE".
except OSError as exc:
if hasattr(exc, 'winerror'):
if exc.winerror == ERROR_INVALID_NAME:
return False
elif exc.errno in {errno.ENAMETOOLONG, errno.ERANGE}:
return False
# If a "TypeError" exception was raised, it almost certainly has the
# error message "embedded NUL character" indicating an invalid pathname.
except TypeError as exc:
return False
# If no exception was raised, all path components and hence this
# pathname itself are valid. (Praise be to the curmudgeonly python.)
else:
return True
# If any other exception was raised, this is an unrelated fatal issue
# (e.g., a bug). Permit this exception to unwind the call stack.
#
# Did we mention this should be shipped with Python already?
def is_path_creatable(pathname: str) -> bool:
'''
`True` if the current user has sufficient permissions to create the passed
pathname; `False` otherwise.
'''
# Parent directory of the passed path. If empty, we substitute the current
# working directory (CWD) instead.
dirname = os.path.dirname(pathname) or os.getcwd()
return os.access(dirname, os.W_OK)
def is_path_exists_or_creatable(pathname: str) -> bool:
'''
`True` if the passed pathname is a valid pathname for the current OS _and_
either currently exists or is hypothetically creatable; `False` otherwise.
This function is guaranteed to _never_ raise exceptions.
'''
try:
# To prevent "os" module calls from raising undesirable exceptions on
# invalid pathnames, is_pathname_valid() is explicitly called first.
return is_pathname_valid(pathname) and (
os.path.exists(pathname) or is_path_creatable(pathname))
# Report failure on non-fatal filesystem complaints (e.g., connection
# timeouts, permissions issues) implying this path to be inaccessible. All
# other exceptions are unrelated fatal issues and should not be caught here.
except OSError:
return False
os.access()
documentation承认:
Note: I/O operations may fail even when
os.access()
indicates that they would succeed, particularly for operations on network filesystems which may have permissions semantics beyond the usual POSIX permission-bit model.
import os, tempfile
def is_path_sibling_creatable(pathname: str) -> bool:
'''
`True` if the current user has sufficient permissions to create **siblings**
(i.e., arbitrary files in the parent directory) of the passed pathname;
`False` otherwise.
'''
# Parent directory of the passed path. If empty, we substitute the current
# working directory (CWD) instead.
dirname = os.path.dirname(pathname) or os.getcwd()
try:
# For safety, explicitly close and hence delete this temporary file
# immediately after creating it in the passed path's parent directory.
with tempfile.TemporaryFile(dir=dirname): pass
return True
# While the exact type of exception raised by the above function depends on
# the current version of the Python interpreter, all such types subclass the
# following exception superclass.
except EnvironmentError:
return False
def is_path_exists_or_creatable_portable(pathname: str) -> bool:
'''
`True` if the passed pathname is a valid pathname on the current OS _and_
either currently exists or is hypothetically creatable in a cross-platform
manner optimized for POSIX-unfriendly filesystems; `False` otherwise.
This function is guaranteed to _never_ raise exceptions.
'''
try:
# To prevent "os" module calls from raising undesirable exceptions on
# invalid pathnames, is_pathname_valid() is explicitly called first.
return is_pathname_valid(pathname) and (
os.path.exists(pathname) or is_path_sibling_creatable(pathname))
# Report failure on non-fatal filesystem complaints (e.g., connection
# timeouts, permissions issues) implying this path to be inaccessible. All
# other exceptions are unrelated fatal issues and should not be caught here.
except OSError:
return False
C:\Windows
中创建文件时或
C:\Windows\system32
目录,UAC 表面上允许用户这样做,同时实际上将所有创建的文件隔离到该用户配置文件中的“虚拟存储”中。 (谁能想到欺骗用户会产生有害的长期后果?)
>>> print('"foo.bar" valid? ' + str(is_pathname_valid('foo.bar')))
"foo.bar" valid? True
>>> print('Null byte valid? ' + str(is_pathname_valid('\x00')))
Null byte valid? False
>>> print('Long path valid? ' + str(is_pathname_valid('a' * 256)))
Long path valid? False
>>> print('"/dev" exists or creatable? ' + str(is_path_exists_or_creatable('/dev')))
"/dev" exists or creatable? True
>>> print('"/dev/foo.bar" exists or creatable? ' + str(is_path_exists_or_creatable('/dev/foo.bar')))
"/dev/foo.bar" exists or creatable? False
>>> print('Null byte exists or creatable? ' + str(is_path_exists_or_creatable('\x00')))
Null byte exists or creatable? False
关于python - 检查路径在 Python 中是否有效,而无需在路径的目标处创建文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9532499/
我需要根据需要动态设置文本区域,但它不想正常工作。 JQuery 会自行检查,但无法检查是否已检查。但是当您在第二个单选框内单击时,始终需要文本区域。我尝试了很多次让它工作,但它仍然有问题。我添加了“
我需要在 Django 中进行 API 调用(某种形式),作为我们所需的自定义身份验证系统的一部分。用户名和密码通过 SSL 发送到特定 URL(对这些参数使用 GET),响应应该是 HTTP 200
我将在我的可移植 C 代码中使用 #warning 来生成编译时警告。但并非所有平台都支持 #warning。有什么方法可以找到该平台是否支持 #warning。 #ifdef warning
我编写了一个函数来检查某个数字是否存在于某个区间内。停止搜索的最佳方法是什么?这个: for (i = a; i <= b; i++) { fi = f(i); if (fi == c) {
我想知道在 c 中是否有一种方法可以检查,例如在 for 函数中,如果变量等于或不等于某些字符,而不必每次都重复进行相等性检查。如果我没记错的话,以这种方式检查相等性是不正确的: if (a == (
我有如下日志功能 void log_error(char * file_name, int line_num, int err_code) { printf("%s:%d:%s\n", fil
使用 ssh-keygen 生成的 key 对在 macOS 上可以有不同的格式。 macOS 可读的标准 PEM ASN.1 对象 SecKey API 带有文本标题的 PEM OpenSSH ke
我正在尝试编写一个 excel if 语句。我不熟悉使用 Excel 具有的所有额外功能。我正在使用一个名为 importXML() 的函数.我正在尝试检查我正在使用的函数是否生成“#VALUE!”错
有没有办法检查是否没有 AIO 写入给定文件?我在我的 Unix 类(class)上制作了一个项目,该项目将是一个上下文无关(基于 UDP)的国际象棋服务器,并且所有数据都必须存储在文件中。应用程序将
我有一个如下所示的函数: public Status execute() { Status status = doSomething(); if (status != Stat
我正在使用 Composer,我不希望 PhpStorm 在 vendor 文件夹上运行任何错误检查或检查,因为它对 vendor/中的某些代码显示误报composer/autoload_static
Chapel 的一个很好的特性是它区分了数组的域和它的分布。检查两个数组是否具有相同的域和分布(通常想要的)的最佳方法是什么? 我能看到的最好的方法是检查 D1==D2和 D1.dist==D2.di
在我的 JavaScript 函数中,我为所有输入、文本区域和选择字段提供实际值作为 initial_value: $('input, textarea, select').each(function
我正在编写一个分解为几个简单函数的 PHP 类。在构造函数中,它调用另一个名为 processFile 的函数。该函数调用 5 个私有(private)函数并进行检查。如果检查失败,它会将消息分配给
这个问题已经有答案了: How to detect if user it trying to open a link in a new tab? (2 个回答) 已关闭 7 年前。 我认为 JavaS
我正在浏览我们的代码库并看到很多这样的测试: declare @row_id int = ... declare @row_attribute string select @row_attribu
我正在声明一个用作比较的函数。我的问题是: 为什么条件充当语句? 为什么第 4 行可以工作,而第 5 行却不行? 我知道这段代码不切实际且未使用,但为什么编译器允许这种语法? 谷歌没有找到答案。但话又
到目前为止,我有一个带有空文本字段的 PHP Kontaktform,并使用以下命令检查了所需的字段: $name = check_input($_POST['name'], "请输入姓名。"); 现
目前,我能想到的合理检查的唯一方法没有臃肿的逻辑: if ( $value > 0 ) { // Okay } else { // Not Okay } 有没有更好的办法? 最佳答案
我正在尝试运行一个脚本,如果 i 存在(意味着存在 i 值,任何值)或其他部分,我希望运行其中的一部分如果i没有值就运行,有人可以启发我吗? 我说的是 for 循环,比如 for (var i=0;
我是一名优秀的程序员,十分优秀!