0

I'm a beginner with Python and I'm trying to list the contents of a directory which is defined as a variable but to no avail.

This is the code:

#!/usr/bin/python
import os

location = "/home/itaig/testdir"
command = os.system('ls -l')," location"

My aim is to count the number of files in the location and print the number.

How can it be achieved?

Edit #1:

In bash I'd do ls -l $location | wc -l , what would be the equivalent in Python?

In any case, I've looked at the links from the comments but wasn't able to get it to work... can you please show me an example?

Thanks

3
  • Look at this: stackoverflow.com/questions/5533700/python-string-formatting Commented Jul 15, 2015 at 8:32
  • 1
    Your command seems odd: It should read os.system("ls -l " + location). But for listing a directory you can use the glob module, which is a bit easier to handle than calling a system command. Commented Jul 15, 2015 at 8:34
  • os.system('ls -l {0}'.format(location)) - unix os.system('dir -l {0}'.format(location)) - windows Although it may not be relevant for you, using commands will make this platform specific. Commented Jul 15, 2015 at 9:15

2 Answers 2

0

You can use os.listdir. This is platform independent as the os module will handle the low level work

print len(os.listdir(location))
Sign up to request clarification or add additional context in comments.

Comments

-1

You can use the good old os.popen function:

p = os.popen('ls -l %s' % location)
nb_lines = 0
while p.readline():
  nb_lines += 1

1 Comment

why downvoting? It answers the question and provides and example of string formatting at the same time, and it shows how to read output from a command too

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.