Q:

Advise on os.path

I'm writing a python script to give me the number of files and directories in a given directory and I'm having varying results
For the below code I'm getting incorrect output
#! /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))

When I use the following code it works
#!/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))

So, in the first case it is not working when I give a directory name input via command line and works in the second case for some reason.
Thanks
Syed

[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

Here os.py is the first program in my question above and ford.py is the second

A:

listdir returns list of filenames only, without base path.  Merge these filenames with x to get full 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:
    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))

