是手术室步行()缺少指向目录的符号链接?

2024-09-30 06:25:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个目录包含一些文件,一些目录,一些指向文件的符号链接和一些指向目录的符号链接。在

当我这么做的时候手术室步行()在目录中followlinks=false时,我将获得指向filenames列表和dirnames列表中的目录的文件和符号链接。但是目录的符号链接不会出现在任何地方。这是一个bug还是Python的一个特性,还是我做错了什么?在

我希望指向目录的符号链接显示在filenames列表中,因为它们不是目录而是符号链接,而其他符号链接(指向其他文件)显示在filenames列表中。在

示例: foo目录包含以下内容:

-rw-rw-r-- 4 rikno staff 136 Jan 14 11:10 firefox
lrwxr-xr-x 1 rikno staff   5 Jan 23 13:29 latex -> tetex
lrwxr-xr-x 2 rikno staff  68 Jan 14 11:10 mozilla -> firefox
drwxrwxr-x 3 rikno staff 102 Jan 23 13:29 tetex

我希望如此手术室步行('foo')在第一次迭代中返回

^{pr2}$

或者至少

('foo', ['latex', 'tetex'], ['firefox', 'mozilla'])

但我得到的只是

('foo', ['tetex'], ['firefox', 'mozilla'])

我从来没有得到任何关于symlink latex(指向tetex目录)的信息

已解决:

好的,结果是

('foo', ['latex', 'tetex'], ['firefox', 'mozilla'])

所以目录的符号链接会出现在dirnames列表中。在

我第一次期望指向目录的符号链接在filenames列表中,而从未在dirnames列表中查找,当尝试代码和文件系统以查找链接所在位置或链接“丢失”的原因时,我意外地混淆了我的结果。在

抱歉问你。在


Tags: 文件目录mozilla列表foo链接符号firefox
2条回答

您写道,您调用了os.walk(),并将followlinks设置为False。好吧,那就是expected behavior

By default, walk() will not walk down into symbolic links that resolve to directories. Set followlinks to True to visit directories pointed to by symlinks, on systems that support them.

在我的机器上运行,os.walk()确实显示了所有sym链接:

>>> os.walk("foo").next()
('foo', ['tetex', 'latex'], ['mozilla', 'firefox'])
>>> os.walk("foo", followlinks=False).next()
('foo', ['tetex', 'latex'], ['mozilla', 'firefox'])

我在这里看到的唯一问题是sym链接出现在目录列表中,而不是文件列表中。在

在大多数用例中,这将是预期的行为,因为人们希望能够将文件列表中的所有条目视为文件,而不必检查它是否是sym链接。在

This thread from python-dev简要讨论这个问题。在

"... putting the symlinks-to-directories into the files list instead of the subdirectory list isn't really any better (it just moves the problem to different use cases, such as those that actually want to read the file contents)."

linked issue page

"For example to count the number of lines of all the files under a directory, a code could go like this:

for root, dirs, files in os.walk(top):
    for file in files:
        f = open(file)
        for n, l in enumerate(f, 1):
            pass
        print(file, n)

If, suddently, a symlink to a directory appeared in files, this will break. So I'm not convinced it's worth changing this. A symlink to a directory is not much closer to a file than to a directory, it really depends on the use case."

相关问题 更多 >

    热门问题