如何只获取目录中的文件?

use*_*200 15 python file python-2.7

我有这个代码:

allFiles = os.listdir(myPath)
for module in allFiles:
    if 'Module' in module: #if the word module is in the filename
        dirToScreens = os.path.join(myPath, module)    
        allSreens = os.listdir(dirToScreens)
Run Code Online (Sandbox Code Playgroud)

现在,一切正常,我只需要更改线路

allSreens = os.listdir(dirToScreens)
Run Code Online (Sandbox Code Playgroud)

获取只是文件的列表,而不是文件夹.因此,当我使用

allScreens  [ f for f in os.listdir(dirToScreens) if os.isfile(join(dirToScreens, f)) ]
Run Code Online (Sandbox Code Playgroud)

它说

module object has no attribute isfile
Run Code Online (Sandbox Code Playgroud)

注意:我使用的是Python 2.7

Pau*_* Bu 40

你可以使用os.path.isfile方法:

import os
from os import path
files = [f for f in os.listdir(dirToScreens) if path.isfile(f)]
Run Code Online (Sandbox Code Playgroud)

或者,如果你觉得功能:D

files = filter(path.isfile, os.listdir(dirToScreens))
Run Code Online (Sandbox Code Playgroud)

  • `abspath()`对我来说不起作用,因为它与执行代码的目录相关[link here](http://stackoverflow.com/questions/24705679/misunderstanding-of-python-os-path- abspath).相反,我使用:`files = [f for os.listdir(dirToScreens)中的f如果path.isfile(path.join(dirToScreens,f))]` (3认同)

jua*_*ith 7

"如果你需要一个文件列表,所有文件名都有一定的扩展名,前缀或中间的任何常用字符串,请使用glob而不是编写代码来自己扫描目录内容"

import os
import glob

[name for name in glob.glob(os.path.join(path,'*.*')) if os.path.isfile(os.path.join(path,name))]
Run Code Online (Sandbox Code Playgroud)

  • 由于某种原因,这将为我返回一个空列表... (2认同)