首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >了解python值的迭代

了解python值的迭代
EN

Stack Overflow用户
提问于 2018-07-22 01:38:01
回答 1查看 57关注 0票数 0

我需要帮助理解为什么我不能遍历存储在变量中的ls -ltcrd输出:

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

print test()

我尝试用上面的python代码做的事情相当于shell中的代码:

代码语言:javascript
复制
ls -ltcrd /tmp/* | awk '{print $NF}'

请注意,输出包含/tmp下所有文件的绝对路径。

理想情况下,我希望避免调用任何外部实用程序。但是运行上面所示的代码似乎是获得我想要的东西的最简单方法。

甚至不确定“迭代”是否是用来描述这一点的正确术语。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-22 02:21:22

试试这样的..。

代码语言:javascript
复制
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)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51458565

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档