Use and complete the template provided. The entire template must be completed. If you don't, your post may be deleted!
- The problem statement, all variables and given/known data:
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.
I have two scripts which I have written the first one does not work and second one works
I'm using Python 2.4.3 on CentOS 5.9
- Relevant commands, code, scripts, algorithms:
#! /usr/bin/python
import os
os.system('clear')
x=raw_input('enter a path ')
print (x)
y=os.listdir(x)
print (y)
k=0
m=0
for a in y:
if os.path.isfile(a):
print (a)
k=k+1
elif os.path.isdir(a):
m=m+1
print (a)
print ('files are %d' % (k))
print ('dirs are %d' % (m))
When I run this I get an output as follows
[root@#### python]# python os2.py
enter a path /var
/var
files are 0
dirs are 1
[root@##### python]#
- The attempts at a solution (include all code and scripts):
The following code I have written with few changes works.
#!/usr/bin/python
import os
os.system('clear')
x=raw_input('enter a path ')
os.chdir(x) # change made
y=os.listdir('.')
m=0
k=0
for i in y:
if os.path.isfile(i):
print i
m = m + 1
elif os.path.isdir(i):
print i
k = k + 1
print ("%d is the number of files in %s" % (m,x))
print ("%d is the number of directories in %s" % (k,x))
[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
- Complete Name of School (University), City (State), Country, Name of Professor, and Course Number (Link to Course):
Python Programming
Self - learning
Reference The Python Tutorial � Python v2.7.4 documentation
Note: Without school/professor/course information, you will be banned if you post here! You must complete the entire template (not just parts of it).