2013-05-02 28 views
1

我正在写一个python脚本来给我的文件和目录的数量在给定的目录,我有不同的结果建议对os.path中

对于下面的代码我得到不正确的输出

#! /usr/bin/python 
import os 
os.system('clear') 

x=raw_input('enter a path ') 
y=os.listdir(x) 
k=0 
m=0 
for a in y: 
     if os.path.isfile(a): 
       k=k+1 
     elif os.path.isdir(a): 
       m=m+1 



print ('files are %d' % (k)) 
print ('dirs are %d' % (m)) 

当我使用下面的代码它的工作原理

#!/usr/local/bin/python 
import os 
os.system('clear') 
x=os.listdir('.') 
m=0 
n=0 
for a in x: 
     if os.path.isfile(a): 
       m=m+1 
     elif os.path.isdir(a): 
       n=n+1 

print ('%d files and %d directories' % (m,n)) 

所以,它不工作的第一种情况,当我通过命令行提供一个目录名的输入而在第二种情况下适用于某些原因。

感谢 赛义德


[[email protected]##### python]# python ford.py 
enter a path /var 
0 is the number of files in /var 
25 is the number of directories in /var 

[[email protected]#### python]# python os2.py 

enter a path /var 
/var files are 0 dirs are 1 

这里os.py在我上面的问题,ford.py的第一个节目是唯一的文件名的第二

+0

从第1个程序和第2个程序得到的输出是什么。你在窗户上吗? – 2013-05-02 06:06:53

+1

你有不同的shebang行,如果你在相同版本的Python下运行这两个脚本,你会得到相同的输出吗? – tripleee 2013-05-02 06:10:27

+0

您的第一个程序有效。在raw_input之后添加一行以打印x,以便我们可以看到您键入的内容。你是刚进入期间(好)还是期间引号(坏)? – tdelaney 2013-05-02 06:15:39

回答

0

listdir返回列表,没有基本路径。将这些文件名与x合并以获得完整路径。

#! /usr/bin/python 
import os 
os.system('clear') 

x=raw_input('enter a path ') 
y=os.listdir(x) 
k=0 
m=0 
for a in y: 
    p = os.path.join(x, a) # <-- here 
    if os.path.isfile(p): 
     k=k+1 
    elif os.path.isdir(p): 
     m=m+1 

print ('files are %d' % (k)) 
print ('dirs are %d' % (m)) 
+0

谢谢monoid,我现在明白了这个问题 – 2013-05-06 06:19:10