首页 > Python > 我应该如何在 Python 中列出目录的所有文件并将它们添加到 ?list

我应该如何在 Python 中列出目录的所有文件并将它们添加到 ?list

上一篇 下一篇

网友问题:

如何在 Python 中列出目录的所有文件并将它们添加到 ?list

网友回答:

我更喜欢使用该模块,因为它可以进行模式匹配和扩展。glob

import glob
print(glob.glob("/home/adam/*"))

它直观地进行模式匹配

import glob
# All files and directories ending with .txt and that don't begin with a dot:
print(glob.glob("/home/adam/*.txt")) 
# All files and directories ending with .txt with depth of 2 folders, ignoring names beginning with a dot:
print(glob.glob("/home/adam/*/*.txt")) 

它将返回一个包含查询文件和目录的列表:

['/home/adam/file1.txt', '/home/adam/file2.txt', .... ]

请注意,会忽略以点开头的文件和目录,因为这些文件和目录被视为隐藏文件和目录,除非模式类似于 。glob..*

用于转义不打算成为模式的字符串:glob.escape

print(glob.glob(glob.escape(directory_name) + "/*.txt"))

网友回答:

os.listdir() 返回目录中的所有内容,包括文件目录

os.path 只能用于列出文件:isfile()

from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]

或者,os.walk() 为它访问的每个目录生成两个列表 — 一个用于文件,一个用于目录。如果你只想要顶级目录,你可以在它第一次产生时中断:

from os import walk

f = []
for (dirpath, dirnames, filenames) in walk(mypath):
    f.extend(filenames)
    break

或者,更短:

from os import walk

filenames = next(walk(mypath), (None, None, []))[2]  # [] if no file

网友回答:

当前目录中的列表

使用 in 模块,您可以获取当前目录中的文件和文件夹listdiros

import os

arr = os.listdir()

在目录中查找

arr = os.listdir('c:\files')

您可以像这样指定要列出的文件类型glob

import glob

txtfiles = []
for file in glob.glob("*.txt"):
    txtfiles.append(file)

or

mylist = [f for f in glob.glob("*.txt")]

get the full path of only files in the current directory

import os
from os import listdir
from os.path import isfile, join

cwd = os.getcwd()
onlyfiles = [os.path.join(cwd, f) for f in os.listdir(cwd) if 
os.path.isfile(os.path.join(cwd, f))]
print(onlyfiles) 

['G:\getfilesname\getfilesname.py', 'G:\getfilesname\example.txt']

Getting the full path name with os.path.abspath

You get the full path in return

 import os
 files_path = [os.path.abspath(x) for x in os.listdir()]
 print(files_path)
 
 ['F:\documentiapplications.txt', 'F:\documenticollections.txt']

Walk: going through sub directories

os.walk returns the root, the directories list and the files list, that is why I unpacked them in r, d, f in the for loop; it, then, looks for other files and directories in the subfolders of the root and so on until there are no subfolders.

import os

# Getting the current work directory (cwd)
thisdir = os.getcwd()

# r=root, d=directories, f = files
for r, d, f in os.walk(thisdir):
    for file in f:
        if file.endswith(".docx"):
            print(os.path.join(r, file))

To go up in the directory tree

# Method 1
x = os.listdir('..')

# Method 2
x= os.listdir('/')

Get files of a particular subdirectory with os.listdir()

import os

x = os.listdir("./content")

os.walk(‘.’) – current directory

 import os
 arr = next(os.walk('.'))[2]
 print(arr)
 
 >>> ['5bs_Turismo1.pdf', '5bs_Turismo1.pptx', 'esperienza.txt']

next(os.walk(‘.’)) and os.path.join(‘dir’, ‘file’)

 import os
 arr = []
 for d,r,f in next(os.walk("F:\_python")):
     for file in f:
         arr.append(os.path.join(r,file))

 for f in arr:
     print(files)

>>> F:\_python\dict_class.py
>>> F:\_python\programmi.txt

next… walk

 [os.path.join(r,file) for r,d,f in next(os.walk("F:\_python")) for file in f]
 
 >>> ['F:\_python\dict_class.py', 'F:\_python\programmi.txt']

os.walk

x = [os.path.join(r,file) for r,d,f in os.walk("F:\_python") for file in f]
print(x)

>>> ['F:\_python\dict.py', 'F:\_python\progr.txt', 'F:\_python\readl.py']

os.listdir() – get only txt files

 arr_txt = [x for x in os.listdir() if x.endswith(".txt")]
 

Using to get the full path of the filesglob

from path import path
from glob import glob

x = [path(f).abspath() for f in glob("F:\*.txt")]

Using to avoid directories in the listos.path.isfile

import os.path
listOfFiles = [f for f in os.listdir() if os.path.isfile(f)]

Using from Python 3.4pathlib

import pathlib

flist = []
for p in pathlib.Path('.').iterdir():
    if p.is_file():
        print(p)
        flist.append(p)

With :list comprehension

flist = [p for p in pathlib.Path('.').iterdir() if p.is_file()]

Use glob method in pathlib.Path()

import pathlib

py = pathlib.Path().glob("*.py")

Get all and only files with os.walk: checks only in the third element returned, i.e. the list of the files

import os
x = [i[2] for i in os.walk('.')]
y=[]
for t in x:
    for f in t:
        y.append(f)

Get only files with next in a directory: returns only the file in the root folder

 import os
 x = next(os.walk('F://python'))[2]

Get only directories with next and walk in a directory, because in the [1] element there are the folders only

 import os
 next(os.walk('F://python'))[1] # for the current dir use ('.')
 
 >>> ['python3','others']

Get all the names with subdirwalk

for r,d,f in os.walk("F:\_python"):
    for dirs in d:
        print(dirs)

os.scandir() from Python 3.5 and greater

import os
x = [f.name for f in os.scandir() if f.is_file()]

# Another example with `scandir` (a little variation from docs.python.org)
# This one is more efficient than `os.listdir`.
# In this case, it shows the files only in the current directory
# where the script is executed.

import os
with os.scandir() as i:
    for entry in i:
        if entry.is_file():
            print(entry.name)

模板简介:该模板名称为【我应该如何在 Python 中列出目录的所有文件并将它们添加到 ?list】,大小是暂无信息,文档格式为.html,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【Python】栏目查找您需要的精美模板。

相关搜索
  • 下载密码 lanrenmb
  • 下载次数 199次
  • 使用软件 Sublime/Dreamweaver/HBuilder
  • 文件格式 html
  • 文件大小 暂无信息
  • 上传时间 02-07
  • 作者 网友投稿
  • 肖像权 人物画像及字体仅供参考
栏目分类 更多 >
热门推荐 更多 >
html5 微信公众平台 单页式简历模板 微信模板 响应式 微信文章 微信素材 微信图片 企业网站 自适应
您可能会喜欢的其他模板