python中区分大小写的路径比较

发布于 2024-11-23 15:21:13 字数 243 浏览 1 评论 0原文

我必须检查 Mac OS X 中的特定路径是否存在文件。

该目录中有一个名为 foo.F90 的文件。

但是当我执行 if(os.path.exists(PATH_TO_foo.f90)) 时,它返回 true 并且没有注意到 f90 是小写字母,而存在的文件是大写 F90。

我尝试了 open(PATH_TO_foo.f90, "r"),即使这不起作用,

我该如何解决这个问题?

I have to check whether a file is present a particular path in Mac OS X.

There is a file called foo.F90 inside the directory.

But when I do if(os.path.exists(PATH_TO_foo.f90)), it returns true and does not notice that f90 is lower case and the file which exists is upper case F90.

I tried open(PATH_TO_foo.f90, "r"), even this does not work

How do I get around this?

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

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

发布评论

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

评论(7

终止放荡 2024-11-30 15:21:13

正如一些评论者所指出的,Python 并不真正关心不区分大小写的文件系统上路径的大小写,因此路径比较或操作函数都不会真正满足您的需要。

但是,您可以使用 os.listdir() 间接测试这一点,它确实会为您提供目录内容及其实际情况。鉴于此,您可以使用以下命令测试文件是否存在:

'foo.f90' in os.listdir('PATH_TO_DIRECTORY')

As some commenters have noted, Python doesn't really care about case in paths on case-insensitive filesystems, so none of the path comparison or manipulation functions will really do what you need.

However, you can indirectly test this with os.listdir(), which does give you the directory contents with their actual cases. Given that, you can test if the file exists with something like:

'foo.f90' in os.listdir('PATH_TO_DIRECTORY')
葬﹪忆之殇 2024-11-30 15:21:13

这与你的底层操作系统有关,而不是 python。例如,在 Windows 中文件系统不区分大小写,而在 Linux 中则区分大小写。因此,如果我在基于 Linux 的系统上运行相同的检查,就像您正在运行的那样,我将不会得到不区分大小写的匹配 -

>>> os.path.exists('F90')
True
>>> os.path.exists('f90')
False                      # on my linux based OS

不过,如果您真的想获得解决方案,您可以这样做 -

if 'f90' in os.listdir(os.path.dirname('PATH_TO_foo.f90')):
    # do whatever you want to do

This is something related to your underlying Operating system and not python. For example, in windows the filesystem is case-insensitive while in Linux it is case sensitive. So if I run the same check, as you are running, on a linux based system I won't get true for case insensitive matches -

>>> os.path.exists('F90')
True
>>> os.path.exists('f90')
False                      # on my linux based OS

Still if you really want to get a solution around this, you can do this -

if 'f90' in os.listdir(os.path.dirname('PATH_TO_foo.f90')):
    # do whatever you want to do
洋洋洒洒 2024-11-30 15:21:13

对于任何仍在为此苦苦挣扎的人。以下片段对我有用。

from pathlib import Path

def path_exists_case_sensitive(p: Path) -> bool:
    """Check if path exists, enforce case sensitivity.

    Arguments:
      p: Path to check
    Returns:
      Boolean indicating if the path exists or not
    """
    # If it doesn't exist initially, return False
    if not p.exists():
        return False

    # Else loop over the path, checking each consecutive folder for
    # case sensitivity
    while True:
        # At root, p == p.parent --> break loop and return True
        if p == p.parent:
            return True
        # If string representation of path is not in parent directory, return False
        if str(p) not in map(str, p.parent.iterdir()):
            return False
        p = p.parent

For anyone still struggling with this. The following snippet works for me.

from pathlib import Path

def path_exists_case_sensitive(p: Path) -> bool:
    """Check if path exists, enforce case sensitivity.

    Arguments:
      p: Path to check
    Returns:
      Boolean indicating if the path exists or not
    """
    # If it doesn't exist initially, return False
    if not p.exists():
        return False

    # Else loop over the path, checking each consecutive folder for
    # case sensitivity
    while True:
        # At root, p == p.parent --> break loop and return True
        if p == p.parent:
            return True
        # If string representation of path is not in parent directory, return False
        if str(p) not in map(str, p.parent.iterdir()):
            return False
        p = p.parent
反目相谮 2024-11-30 15:21:13

如果系统或您可以使用的路径之间的路径发生变化:

import os, fnmatch

for file in os.listdir('.'):
    if fnmatch.fnmatch(file, 'foo.*'):
        print file

这将返回所有文件 foo.txt。

If the path changes between systems or something you could use:

import os, fnmatch

for file in os.listdir('.'):
    if fnmatch.fnmatch(file, 'foo.*'):
        print file

This will return all files foo.

岁吢 2024-11-30 15:21:13

我认为这应该对你有用 -

    import os  

    def exists(path):  
        import win32api  
        if path.find('/') != -1:  
            msg = 'Invalid path for Windows %s'%path  
            raise Exception(msg)  
        path = path.rstrip(os.sep)  
        try:  
            fullpath = win32api.GetLongPathNameW(win32api.GetShortPathName(path))  
        except Exception, fault:  
            return False  
        if fullpath == path:  
            return True  
        else:
            return False

I think this should work for you -

    import os  

    def exists(path):  
        import win32api  
        if path.find('/') != -1:  
            msg = 'Invalid path for Windows %s'%path  
            raise Exception(msg)  
        path = path.rstrip(os.sep)  
        try:  
            fullpath = win32api.GetLongPathNameW(win32api.GetShortPathName(path))  
        except Exception, fault:  
            return False  
        if fullpath == path:  
            return True  
        else:
            return False
苯莒 2024-11-30 15:21:13

所以,既然你没有区分大小写的文件系统,那么怎么样

import os
if 'foo.F90' in os.listdir(PATH_TO_DIRECTORY):
    open(PATH_TO_DIRECTORY + 'foo.F90')

So, since you do not have a case sensitive filesystem, how about

import os
if 'foo.F90' in os.listdir(PATH_TO_DIRECTORY):
    open(PATH_TO_DIRECTORY + 'foo.F90')
荒路情人 2024-11-30 15:21:13

对于 Python 3.5+,使用 pathlib 可以轻松完成此操作。适用于文件和目录:

from pathlib import Path

def exists_case_sensitive(path) -> bool:
    p = Path(path)
    if not p.exists():
        # If it already doesn't exist(), 
        # we can skip iterdir().
        return False
    return p in p.parent.iterdir()

Easy way to do this for Python 3.5+ using pathlib. Works for files and dirs:

from pathlib import Path

def exists_case_sensitive(path) -> bool:
    p = Path(path)
    if not p.exists():
        # If it already doesn't exist(), 
        # we can skip iterdir().
        return False
    return p in p.parent.iterdir()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文