RoyMWell
RoyMWell

Reputation: 199

understanding iteration of python values

i need help understanding why i cant iterate through the ls -ltcrd output which im storing in a variable:

def test():
    tmplist = os.system('ls -ltcrd /tmp/*')
    tmplist.split(' ')[:1]  #trying to grab the last column here

print test()

What I'm trying to do with the above python code is equivalent to this in shell:

ls -ltcrd /tmp/* | awk '{print $NF}'

Note that the output contains the absolute path of all the files under /tmp.

Ideally, Id like to avoid calling any external utilities. But running it as shown above seems to be the simplest way to get what i want.

not even sure if "iteration" is the right term to use to describe this.

Upvotes: 0

Views: 62

Answers (1)

wg4568
wg4568

Reputation: 319

Try something like this...

import subprocess
import os

# use the subprocess module to get the output of the command
def test(path):
    tmplist = subprocess.check_output(['ls', '-ltcrd', path])
    return tmplist.split()[-1:][0]

# get every filename under /tmp/
files = os.listdir('/tmp/')

# iterate over every filename, and run 'test'
for file in files:
    x = test('/tmp/' + file)
    print(x)

Upvotes: 2

Related Questions