0

I am writing python script, in my python script i want to run "list of files in a directory" using commands.getoutput, my probleam is "i defined the directory path in python variable like "dir_name".I tried with following.

dir_name="/user/pjanga/python_test"
index_list=commands.getoutput('ls -l',dir_name,'| 'wc -l')

Error:-

File "diii.py", line 10
    index_list=commands.getoutput('ls -l',dir_name,'| 'wc -l')
                                                        ^
SyntaxError: invalid syntax

Could you please help me out run?

1
  • 2
    I Think syntax highlighting says it all... Commented Jan 28, 2017 at 13:22

2 Answers 2

2

Several problems here, try:

index_list = commands.getoutput('ls -l ' + dir_name + ' | wc -l')

String concatenation is a +, not a comma, and you had an uneven number of single quotes. Note also the space after the ls -l.

However, there are far better ways to do this. First of all the answer does not represent the number of files in the directory. Do an ls -l on the command-line and you will see that the first line is "total", not a filename (this is historical and represents the number of blocks, and is pretty useless).

If you used ls instead of ls -l you would not get this issue.

However, there is no need to call two separate external programs, use python:

import os
index_list = len([name for name in os.listdir(dir_name) ])

Here we call os.listdir() and create a list of filenames, then just get the number of items in that list.

There are several other ways to do this in python.

Sign up to request clarification or add additional context in comments.

Comments

0

There are different ways to execute the command from python in Linux machine.

Method 1:

index_list = commands.getoutput('ls -l ' + dir_name + ' | wc -l')

Method 2:

import os
os.system("ls -l ' + dir_name + ' | wc -l')

Method 3:

import subprocess
index_list = subprocess.check_output('ls -l ' + dir_name + ' | wc -l, shell=True) 

Hope it helps !!

Comments

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.