简体   繁体   English

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

[英]How to get contents of a given "path" using 'ls -l' command and Python

I am using python and i want to get listing of all of the files /directories (not nested) at a given path.我正在使用 python,我想获得给定路径中所有文件/目录(非嵌套)的列表。 Meaning i need exact equivalent out put of "ls -l" command using python.这意味着我需要使用 python 完全等效的“ls -l”命令输出。

For eg at path /opt/test/ ls -l out put is shown below.例如在路径 /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

My python code is shown below.我的python代码如下所示。

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

How can i pass the path value ie "/opt/temp" and get the same put of "ls -l" as shown above?我如何传递路径值,即“/opt/temp”并获得与上图相同的“ls -l”?

You are far, far better off using os.listdir , which essentially exactly what you want.使用os.listdir效果要好得多,这基本上正是您想要的。

You can also use os.scandir if you need other information about these folders, though you'll need to filter to ensure you're only picking up folders:如果您需要有关这些文件夹的其他信息,您也可以使用os.scandir ,但您需要进行过滤以确保您只选择文件夹:

[e for e in os.scandir() if e.isdir]

Each of these functions takes a path argument if you want to explicitly specify it, otherwise they run on the current directory.如果您想明确指定,这些函数中的每一个都需要一个路径参数,否则它们会在当前目录上运行。

You can use pathlib.Path() for this (Python >=3.4):您可以pathlib.Path()使用pathlib.Path() (Python >=3.4):

from pathlib import Path

source = Path('/opt/temp')

# Get all children
content = source.glob('*')

By default this will return an iterator of pathlib.Path objects (cast iterator to list if you need a visual check).默认情况下,这将返回pathlib.Path对象的迭代器(如果您需要视觉检查, pathlib.Path迭代器转换为列表)。 Then you can programmatically access file attributes using pahtlib.Path.stat() .然后您可以使用pahtlib.Path.stat()编程方式访问文件属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM