Python os.path.isdir为点返回true

morha13

我正在用python编写自己的shell。现在,我正在尝试cd对我的shell执行该命令。

执行此命令的函数有几个变量:

self.current_dir = "C:\\" -默认值,它的变化取决于使用cd命令的用户输入

dir = "..."-用户键入的请求目录。“ ...”是导致问题的输入的示例。

这是我的代码:

def command_cd(self, dir):
    if os.path.isdir(self.shell.current_dir + dir):
        self.shell.current_dir = self.shell.current_dir + dir + "\\"

问题是由于某种奇怪的原因,当用户键入点时os.path.isdir(self.shell.current_dir + dir)返回True(就像我上面给出的变量的示例输入一样)。

即使更改点数(甚至超过5个点),也会出现问题,我真的不知道是什么原因造成的。

显然没有命名的文件夹...或类似的名称。

如果我的问题还不够清楚,请发表评论,我会对其进行编辑

abccd

.是当前目录,..是父目录,没有大于两个点的引用。

但是,为什么os.path.isdir()返回True的原因是因为python将大于两个点的所有内容都注册为一个点。

import os

print(os.path.abspath(".......") == os.path.abspath("."))
print(os.path.abspath("....") == os.path.abspath("."))

# and that
print(os.path.samefile('......', '.'))
# also prints True

从开始....它们都将打印True,........指向同一位置。


作为chepner在评论中所指出的那样,不会发生此问题在POSIX系统,而它是由导致os.stat错误地等同于'....''.'(这是不是这种情况,请参阅下文编辑)


重要编辑:

eriksun评论:

窗口os.path.isdir是通过调用来实现GetFileAttributes,这就要求NtQueryAttributesFile像所有文件系统功能一样,它首先必须将DOS路径转换为本NT路径。对于内核来说"."".."它们只是普通名称,因此运行时库首先必须通过函数对路径进行规范化,该函数RtlGetFullPathName_Ustr也将由所使用os.path.abspath,因此结果是相似的。它在最终组件中减少两个以上点和尾部空格的方式是从继承的DOS它正在努力效仿OS1980年代的。

因此,此问题与python本身无关,因为Windows cmd中也会发生此问题,cd c:\.....或者cd .\....\..Windows仍然可以通过引用两个点而不是两个点来使您摆脱它。因为它是从继承而来,所以DOS可以将两个以上的点减少为一个并删除尾随空格。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

os.path.isdir()和os.path.isfile()都在脚本中返回False,但在Python控制台中返回True(就像应该那样)

python 2.7 os.path.isdir(unicode abspath字符串)什么都不返回

python os.path.isfile()对于标量返回true

python os.path.isfile()对于某些整数返回True

python os.path.exists 返回 false

python 函数 os.path.exists() 当我给一个 bool 值时返回 True

python中的os.path.join返回“错误”路径?

为OS X Python virtualenv安装创建PATH

奇怪的行为os.path.isdir(x)

os.path.isdir()在无法访问但现有目录上返回false

os.path.isdir()向现有文件夹返回false

对python os.path.abspath的误解

清单上的Python os.path.join()

Windows上的Python os.path.join

Python os.path.basename,带状参数

Python的os.path.relpath的异常行为

os.path.exists与os.path.isdir之间的优缺点

os.path.normpath() 在 ubuntu 中比较 python 中的两个路径时返回 False

os.path.split似乎返回错误

os.path.exists()始终返回false

Java 中的 Python os.path.dirname 和 os.path.sep?

为什么写“from os import path.isfile, path.isdir, scandir”无效?

对于现有的文件系统对象,os.path.isfile 是否总是与 os.path.isdir 相反?

Python os.path.getmtime 在 UTC 为什么

在Mac OS PATH中删除Python 3.8条目

Python使用os.path lib获取文件名

如何规避Python的os.path.commonprefix的谬误?

Python os.path.commonprefix-是否存在面向路径的函数?

添加到python path mac os x