简体   繁体   English

Python os listdir在Mac中无法正常工作

[英]Python os listdir not working properly in Mac

I am trying to list all folders of a directory using python in Mac os 10.8.2. 我试图在Mac OS 10.8.2中使用python列出目录的所有文件夹。

My code is as simple as this: 我的代码很简单:

#!/usr/bin/env python
#coding: utf8
import os
print [name for name in os.listdir(os.path.abspath('.')) if os.path.isdir(name)]

When I run this script in a path where there are folders the outcome is: 当我在有文件夹的路径中运行此脚本时,结果是:

[]

I try this same script in another computer (ubuntu) and it works perfectly, listing all the directories in the current path. 我在另一台计算机(ubuntu)上尝试了相同的脚本,它运行良好,列出了当前路径中的所有目录。


I have tried exactly the same in the python console in that path and it works, the outcome is: 我在该路径的python控制台中尝试了完全相同的方法,并且可以正常工作,结果是:

['Final', 'Script_actualizacion', 'Z_L1']

What could be happening? 可能会发生什么?

Ok now this is working: 好的,现在可以正常工作了:

#!/usr/bin/env python
#coding: utf8
import os
path = os.path.abspath('.')
print [name for name in os.listdir(path) if os.path.isdir(os.path.join(path,name))]

The problem happened because I was calling the python from a different location so it checked the dirs in the wrong path. 发生问题是因为我从另一个位置调用了python,所以它检查了错误路径中的dirs。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM