我正在编写python脚本,以给出给定目录中的文件和目录的数量,并且我有不同的结果
对于下面的代码,我得到了不正确的输出
#! /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))因此,在第一种情况下,当我通过命令行输入目录名时,由于某种原因,在第二种情况下,它无法工作。
谢谢赛义德
[root@##### python]# python ford.py
enter a path /var
0 is the number of files in /var
25 is the number of directories in /var
[root@#### python]# python os2.py
enter a path /var
/var files are 0 dirs are 1在这里,os.py是我上面问题中的第一个程序,ford.py是第二个程序
发布于 2013-05-03 14:17:09
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))https://stackoverflow.com/questions/16331273
复制相似问题