os.listdir 和 os.path.isdir 混淆,isdir 是随机行为吗? [英] os.listdir and os.path.isdir confusion, isdir is acting random?

查看:59
本文介绍了os.listdir 和 os.path.isdir 混淆,isdir 是随机行为吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面有一个简单的过程来列出文件夹的内容:

I have this simple process below for listing the contents of a folder:

def some_process(self):


    dir3 = os.listdir('/Users/somepath/programming/somepathanother/Data_samples')
    for d in dir3:
        if os.path.isdir(d):
            print "DIR: " + d
        elif os.path.isfile(d):
            print "FILE: " + d


    print "PATH THREE:"
    print str(dir3)

    sys.exit(0) 

Data_samples 文件夹的实际内容是:目录 1目录2目录3目录 4文件.zip另一个文件.zip目录5

The actual contents of the Data_samples folder is: dir1 dir2 dir3 dir4 file.zip anotherfile.zip dir5

过程的输出没有按预期工作.对于一个文件,它只是打印:

The output of the process does not work as expected. For a file it just prints:

FILE .DS_Store没有别的(应该打印出file.zip和anotherfile.zip)

FILE .DS_Store and nothing else (should print out file.zip and anotherfile.zip)

我也意识到,如果我将 resourcetest.py 文件及其对应的 ini 文件复制到此文件夹中并运行它,那么它确实会看到它

I also realize that if I copy the resourcetest.py file and it's corresponding ini file into this folder and run it then it does see it

FILE: .DS_Store
FILE: resourcetest.ini
FILE: resourcetest.py

print str(dir3)

PATH THREE: 
['.DS_Store', 'dir1', 'dir2', 'dir3', 'dir4', 'resourcetest.ini','resourcetest.py', 'test.file', 'test.zip', 'dir5']

然后还应该将 dir1 dir2 dir3 dir4 打印为 DIR: " ,但这些都没有发生,我不知道为什么,尽管如果我从列出的文件夹中执行此代码会有些奇怪,但它确实显示了所有内容正确.

Then should also print out dir1 dir2 dir3 dir4 as DIR: " , yet none of this happens and I have no idea why, though in an odd twist if I execute this code from the folder that is listed, it does show everything correctly.

这是从 mac os x 终端运行 python 2.7 的异常,还是我在这里遗漏了其他东西.我对 listdir 和 isdir 的使用的想法是错误的吗?

Is this an anomaly of running python 2.7 from the mac os x terminal, or am I missing something else here. Is my thinking on the usage of listdir and isdir wrong?

推荐答案

listdir 仅提供名称,而不提供完整路径.您需要创建完整路径:

listdir gives only the names, not the full path. You will need to create the full path:

for d in dir3:
    path = os.path.join('/Users/somepath/programming/somepathanother/Data_samples', d)
    if os.path.isdir(path):
        ...

这篇关于os.listdir 和 os.path.isdir 混淆,isdir 是随机行为吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆