Is os.walk() missing symlinks to directories?

点点圈 提交于 2019-12-06 05:44:32

Running on my machine, os.walk() does show all the sym links:

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

The only 'problem' I see here is that the sym link appears in the list of directories and not in the list of files.

In most use cases, this would be the expected behaviour since one would expect to be able to treat all entries in the file-list as files and not have to check if it is a sym-link or not.

This thread from python-dev briefly discusses the issue.

"... 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)."

and from the 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."

You wrote that you called os.walk() with followlinks set to False. Well, then that's the 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!