python中区分大小写的路径比较
我必须检查 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
正如一些评论者所指出的,Python 并不真正关心不区分大小写的文件系统上路径的大小写,因此路径比较或操作函数都不会真正满足您的需要。
但是,您可以使用 os.listdir() 间接测试这一点,它确实会为您提供目录内容及其实际情况。鉴于此,您可以使用以下命令测试文件是否存在:
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:这与你的底层操作系统有关,而不是 python。例如,在 Windows 中文件系统不区分大小写,而在 Linux 中则区分大小写。因此,如果我在基于 Linux 的系统上运行相同的检查,就像您正在运行的那样,我将不会得到不区分大小写的匹配 -
不过,如果您真的想获得解决方案,您可以这样做 -
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 -
Still if you really want to get a solution around this, you can do this -
对于任何仍在为此苦苦挣扎的人。以下片段对我有用。
For anyone still struggling with this. The following snippet works for me.
如果系统或您可以使用的路径之间的路径发生变化:
这将返回所有文件 foo.txt。
If the path changes between systems or something you could use:
This will return all files foo.
我认为这应该对你有用 -
I think this should work for you -
所以,既然你没有区分大小写的文件系统,那么怎么样
So, since you do not have a case sensitive filesystem, how about
对于 Python 3.5+,使用
pathlib
可以轻松完成此操作。适用于文件和目录:Easy way to do this for Python 3.5+ using
pathlib
. Works for files and dirs: