如何使用'ls -l'命令和Python获取给定“路径”的内容

问题描述 投票:-2回答:2

我正在使用python,我想获取给定路径下所有文件/目录的列表(未嵌套)。这意味着我需要使用python“ ls -l”命令的完全等效输出。

例如在路径/ opt / test / ls -l下显示如下。

-rw-r--r--  1 user  qa-others  16715 Jan 16 13:38 file_2001161337
-rw-r--r--  1 user  qa-others  16715 Jan 16 13:46 file_2001161346
-rw-r--r--  1 user  qa-others  16715 Jan 16 13:54 file_2001161353

我的python代码如下所示。

print(subprocess.check_output(['ls', '-l']))

如何传递路径值,即“ / opt / temp”,并获得与上述相同的“ ls -l”的位置?

python subprocess ls
2个回答
0
投票

您可以为此使用pathlib.Path()(Python> = 3.4):

pathlib.Path()

默认情况下,它将返回一个from pathlib import Path source = Path('/opt/temp') # Get all children content = source.glob('*') 对象的迭代器(如果需要视觉检查,则将迭代器投射到列表中)。然后,您可以使用pathlib.Path以编程方式访问文件属性。


0
投票

您使用pahtlib.Path.stat()的效果要好得多,基本上是您想要的。

如果需要获取有关这些文件夹的信息,也可以使用pahtlib.Path.stat()。>>

© www.soinside.com 2019 - 2024. All rights reserved.