如何在Python中列出目录的内容?

问题:如何在Python中列出目录的内容?

不能很难,但是我有一个精神障碍。

Can’t be hard, but I’m having a mental block.


回答 0

import os
os.listdir("path") # returns list
import os
os.listdir("path") # returns list

回答 1

单程:

import os
os.listdir("/home/username/www/")

另一种方式

glob.glob("/home/username/www/*")

在这里找到示例

glob.glob上面的方法不会列出隐藏文件。

自从几年前我最初回答这个问题以来,pathlib已添加到Python。我现在列出目录的首选方法通常涉及对象的iterdir方法Path

from pathlib import Path
print(*Path("/home/username/www/").iterdir(), sep="\n")

One way:

import os
os.listdir("/home/username/www/")

Another way:

glob.glob("/home/username/www/*")

Examples found here.

The glob.glob method above will not list hidden files.

Since I originally answered this question years ago, pathlib has been added to Python. My preferred way to list a directory now usually involves the iterdir method on Path objects:

from pathlib import Path
print(*Path("/home/username/www/").iterdir(), sep="\n")

回答 2

os.walk 如果需要递归可以使用:

import os
start_path = '.' # current directory
for path,dirs,files in os.walk(start_path):
    for filename in files:
        print os.path.join(path,filename)

os.walk can be used if you need recursion:

import os
start_path = '.' # current directory
for path,dirs,files in os.walk(start_path):
    for filename in files:
        print os.path.join(path,filename)

回答 3

glob.globos.listdir将会做到。

glob.glob or os.listdir will do it.


回答 4

os模块处理所有这些东西。

os.listdir(path)

返回一个列表,其中包含由path给出的目录中条目的名称。该列表是任意顺序的。它不包括特殊条目“。” 和“ ..”,即使它们存在于目录中。

可用性:Unix,Windows。

The os module handles all that stuff.

os.listdir(path)

Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order. It does not include the special entries ‘.’ and ‘..’ even if they are present in the directory.

Availability: Unix, Windows.


回答 5

在Python 3.4+中,您可以使用新pathlib软件包:

from pathlib import Path
for path in Path('.').iterdir():
    print(path)

Path.iterdir()返回一个迭代器,可以很容易地将其变成list

contents = list(Path('.').iterdir())

In Python 3.4+, you can use the new pathlib package:

from pathlib import Path
for path in Path('.').iterdir():
    print(path)

Path.iterdir() returns an iterator, which can be easily turned into a list:

contents = list(Path('.').iterdir())

回答 6

从Python 3.5开始,您可以使用os.scandir

区别在于它返回文件条目而不是名称。在某些操作系统(例如Windows)上,这意味着您不必os.path.isdir/file知道它是否是文件,并且可以节省CPU时间,因为stat在Windows中扫描目录时已完成此操作:

列出目录并打印大于max_value字节的文件的示例:

for dentry in os.scandir("/path/to/dir"):
    if dentry.stat().st_size > max_value:
       print("{} is biiiig".format(dentry.name))

在此处阅读基于性能的详尽答案)

Since Python 3.5, you can use os.scandir.

The difference is that it returns file entries not names. On some OSes like windows, it means that you don’t have to os.path.isdir/file to know if it’s a file or not, and that saves CPU time because stat is already done when scanning dir in Windows:

example to list a directory and print files bigger than max_value bytes:

for dentry in os.scandir("/path/to/dir"):
    if dentry.stat().st_size > max_value:
       print("{} is biiiig".format(dentry.name))

(read an extensive performance-based answer of mine here)


回答 7

下面的代码将列出目录和目录中的文件。另一个是os.walk

def print_directory_contents(sPath):
        import os                                       
        for sChild in os.listdir(sPath):                
            sChildPath = os.path.join(sPath,sChild)
            if os.path.isdir(sChildPath):
                print_directory_contents(sChildPath)
            else:
                print(sChildPath)

Below code will list directories and the files within the dir. The other one is os.walk

def print_directory_contents(sPath):
        import os                                       
        for sChild in os.listdir(sPath):                
            sChildPath = os.path.join(sPath,sChild)
            if os.path.isdir(sChildPath):
                print_directory_contents(sChildPath)
            else:
                print(sChildPath)