Python 只列出目录中的文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14176166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:40:08  来源:igfitidea点击:

List only files in a directory?

python

提问by tkbx

Is there a way to list the files (not directories) in a directory with Python? I know I could use os.listdirand a loop of os.path.isfile()s, but if there's something simpler (like a function os.path.listfilesindiror something), it would probably be better.

有没有办法用 Python 列出目录中的文件(而不是目录)?我知道我可以使用sos.listdir循环os.path.isfile(),但如果有更简单的东西(比如函数os.path.listfilesindir或其他东西),它可能会更好。

采纳答案by Gareth Latty

This is a simple generator expression:

这是一个简单的生成器表达式

files = (file for file in os.listdir(path) 
         if os.path.isfile(os.path.join(path, file)))
for file in files: # You could shorten this to one line, but it runs on a bit.
    ...

Or you could make a generator function if it suited you better:

或者你可以制作一个更适合你的生成器函数:

def files(path):
    for file in os.listdir(path):
        if os.path.isfile(os.path.join(path, file)):
            yield file

Then simply:

然后简单地:

for file in files(path):
    ...

回答by riamse

You could try pathlib, which has a lot of other useful stuff too.

您可以尝试pathlib,它也有很多其他有用的东西。

Pathlib is an object-oriented library for interacting with filesystem paths. To get the files in the current directory, one can do:

Pathlib 是一个面向对象的库,用于与文件系统路径交互。要获取当前目录中的文件,可以执行以下操作:

from pathlib import *
files = (x for x in Path(".") if x.is_file())
for file in files:
    print(str(file), "is a file!")

This is, in my opinion, more Pythonic than using os.path.

在我看来,这比使用os.path.

See also: PEP 428.

另见:PEP 428

回答by Noam Manos

Using pathlib in Windows as follow:

在 Windows 中使用 pathlib 如下:

files = (x for x in Path("your_path") if x.is_file())

files = (x for x in Path("your_path") if x.is_file())

Generates error:

产生错误:

TypeError: 'WindowsPath' object is not iterable

类型错误:“WindowsPath”对象不可迭代

You should rather use Path.iterdir()

你应该使用Path.iterdir()

filePath = Path("your_path")
if filePath.is_dir():
    files = list(x for x in filePath.iterdir() if x.is_file())

回答by johnson

files = next(os.walk('..'))[2]

回答by bold

Using pathlib, the shortest way to list only files is:

使用pathlib,仅列出文件的最短方法是:

[x for x in Path("your_path").iterdir() if x.is_file()]

with depth support if need be.

如果需要,可以提供深度支持。

回答by Neil

For the special case of working with files in the current directory, you could do it as a simple one-liner list comprehension:

对于处理当前目录中的文件的特殊情况,您可以将其作为简单的单行列表理解:

[f for f in os.listdir(os.curdir) if os.path.isfile(f)]

Otherwise in the more general case, directory paths & filenames have to be joined:

否则,在更一般的情况下,必须加入目录路径和文件名:

dirpath = '~/path_to_dir_of_interest'
files = [f for f in os.listdir(dirpath) if os.path.isfile(os.path.join(dirpath, f))]

回答by acaruci

Since Python 3.6 you can use glob with a recursive option "**". Note that glob will give you all files and directories, so you can keep only the ones that are files

从 Python 3.6 开始,您可以使用带有递归选项“**”的 glob。请注意, glob 将为您提供所有文件和目录,因此您只能保留文件和目录

files = glob.glob(join(in_path, "**/*"), recursive=True)
files = [f for f in files if os.path.isfile(f)]

回答by PetitBrezhoneg

If you use Python 3, you could use pathlib.

如果您使用 Python 3,则可以使用pathlib

But, you have to know that if you use the is_dir()method as :

但是,您必须知道,如果您将is_dir()方法用作:

from pathlib import *

#p is directory path
#files is list of files in the form of path type

files=[x for x in p.iterdir() if x.is_file()]

empty files will be skipped by .iterdir()

空文件将被跳过 .iterdir()

The solution I found is:

我找到的解决方案是:

from pathlib import *

#p is directory path

#listing all directory's content, even empty files
contents=list(p.glob("*"))

#if element in contents isn't a folder, it's a file
#is_dir() even works for empty folders...!

files=[x for x in contents if not x.is_dir()]