Help with subprocess.check_output command

0

I have to make a program that takes the list of files from a directory and save them in an array to see if they are files or folders. I have the following code:

#!/usr/bin/python
import subprocess, os
array = subprocess.check_output(["ls","-a","/usr/bin/"])
for h in array:
    if os.path.isdir(h):
        print 'bandera1'
    else:
        print 'bandera2'

but at the time of doing that, it takes character by character of the variablle array, how could I take the complete word corresponding to the file name?

    
asked by user29937 14.02.2017 в 01:27
source

1 answer

0

It takes character by character because the result of check_output is a text string (not an array) and the iteration of a string is done character by character.

You could start that chain in each line break, with what you would have:

for h in array.split('\n'):
    ...

But it's even better that you use os.listdir() , which is much cleaner and direct, and also returns an array directly.

import os
path = '/usr/bin/'
for h in os.listdir(path):
    if os.path.isdir(os.path.join(path, h)):
        ...
    else:
        ...

Notice that we use os.path.join() to reconstruct the route to the file (since os.listdir() does not include the route in the results, which happens also in the ls of your example).

If you additionally need to go through the subdirectories, it is usually more appropriate to use os.walk() , which also gives you listings of directories and files already separated into two different arrays ( link ).

    
answered by 14.02.2017 в 18:21