如何使用 python 从包含数千个文件的目录中复制前 100 个文件?

2023-12-03

我有一个巨大的目录,并且一直在更新。我试图使用 python 仅列出目录中最新的 100 个文件。我尝试使用 os.listdir(),但是当目录大小接近 1,00,000 个文件时,listdir() 似乎崩溃了(或者我没有等待足够长的时间)。我只需要前 100 个文件(或文件名)进行进一步处理,因此我不希望 listdir() 填充所有 100000 个文件。在Python中有没有好的方法可以做到这一点?

PS:我对编程很陌生


这是关于如何逐个文件遍历大目录的答案!

我疯狂地寻找 Windows DLL,它可以让我做 Linux 上所做的事情,但没有成功。

因此,我得出的结论是,唯一的方法是创建自己的 DLL,将这些静态函数公开给我,但后来我想起了 pywintypes。 而且,耶!这已经在那里完成了。而且,更重要的是,迭代器函数已经实现了!凉爽的!

带有 FindFirstFile()、FindNextFile() 和 FindClose() 的 Windows DLL 可能仍在某处,但我没有找到它。所以,我使用了 pywintypes。

编辑: 我发现(很晚)这些函数可以从 kernel32.dll 中获得。一直躲在我的鼻子前面。

抱歉产生依赖性。但我认为您可以从 ...\site-packages\win32 文件夹和最终依赖项中提取 win32file.pyd ,并在必要时将其独立于您的程序的 win32types 进行分发。

正如您从速度测试中看到的那样,返回生成器非常快。

之后,您将能够逐个文件进行操作并执行您想做的任何操作。

NOTE: win32file.FindFilesIterator() returns whole stat of the file/dir, therefore, using my listdir() to get the name and afterwards os.path.get*time() or os.path.is*() doesn't make sense. Better modify my listdir() for those checks.

现在,获得问题的完整解决方案仍然是个问题。

对您来说坏消息是,它从它喜欢的目录中的第一项开始,您无法选择它是哪一项。在我的测试中它总是返回排序的目录。 (在 Windows 上)

好消息是,您可以在 Windows 上使用通配符来控制要列出的文件。因此,要在不断填充的目录上使用它,您可以使用版本标记新的文件并执行以下操作:

bunch = 1
while True:
    for file in listdir("mydir\\*bunch%i*" % bunch): print file
    sleep(5); bunch += 1

但您必须非常巧妙地设计这一点,否则您将收到文件,但由于迟到而找不到它们。

我不知道如果您在循环之间引入延迟,FindFilesIterator() 是否会在新文件到来时继续检测它们。

如果确实如此,这也可能是您的解决方案。

你总是可以提前创建一个迭代器,然后调用 next() 方法来获取下一个文件:

i = listdir(".")
while True:
    try: name = i.next()
    except StopIteration: sleep(1)
# This probably won't work as imagined though

您可以根据最后到达的文件的大小来决定等待新文件的时间。疯狂猜测所有传入文件的大小大致相同,加上或减去一些内容。

然而,win32file 为您提供了一些功能,可以帮助您监视目录的更改,我认为这是您最好的选择。

在速度测试中,您还可以看到从此迭代器构造列表比调用 os.listdir() 慢,但 os.listdir() 会阻塞,而我的 listdir() 不会。 无论如何,它的目的不是创建文件列表。我不知道为什么会出现这种速度损失。只能猜测有关 DLL 调用、列表构造、排序或类似内容的内容。 os.listdir() 完全用 C 编写。

你可以在 if 中看到一些用法name=="main“块。将代码保存在listdir.py中并'from listdir import *'它。

Here is the code:


#! /usr/bin/env python

"""
An equivalent of os.listdir() but as a generator using ctypes on 
Unixoides and pywintypes on Windows.

On Linux there is shared object libc.so that contains file manipulation 
functions we need: opendir(), readdir() and closedir().
On Windows those manipulation functions are provided 
by static library header windows.h. As pywintypes is a wrapper around 
this API we will use it.
kernel32.dll contains FindFirstFile(), FindNextFile() and FindClose() as well and they can be used directly via ctypes.

The Unix version of this code is an adaptation of code provided by user
'jason-orendorff' on Stack Overflow answering a question by user 'adrien'.
The original URL is:
http://stackoverflow.com/questions/4403598/list-files-in-a-folder-as-a-stream-to-begin-process-immediately

The Unix code is tested on Raspbian for now and it works. A reasonable 
conclusion is that it'll work on all Debian based distros as well.

NOTE: dirent structure is not the same on all distros, so the code will break on some of them.

The code is also tested on Cygwin using cygwin1.dll and it 
doesn't work.

If platform isn't Windows or Posix environment, listdir will be 
redirected back to os.listdir().

NOTE: There is scandir module implementing this code with no dependencies, excellent error handling and portability. I found it only after putting together this code. scandir() is now included in standardlib of Python 3.5 as os.scandir().
You definitely should use scandir, not this code.
Scandir module is available on pypi.python.org.
"""

import sys, os

__all__ = ["listdir"]

if sys.platform.startswith("win"):
    from win32file import FindFilesIterator

    def listdir (path):
        """
        A generator to return the names of files in the directory passed in
        """
        if "*" not in path and "?" not in path:
            st = os.stat(path) # Raise an error if dir doesn't exist or access is denied to us
            # Check if we got a dir or something else!
            # Check gotten from stat.py (for fast checking):
            if (st.st_mode & 0170000) != 0040000:
                e = OSError()
                e.errno = 20; e.filename = path; e.strerror = "Not a directory"
                raise e
            path = path.rstrip("\\/")+"\\*"
        # Else:  Decide that user knows what she/he is doing
        for file in FindFilesIterator(path):
            name = file[-2]
            # Unfortunately, only drives (eg. C:) don't include "." and ".." in the list:
            if name=="." or name=="..": continue
            yield name

elif os.name=="posix":
    if not sys.platform.startswith("linux"):
        print >> sys.stderr, "WARNING: Environment is Unix but platform is '"+sys.platform+"'\nlistdir() may not work properly."
    from ctypes import CDLL, c_char_p, c_int, c_long, c_ushort, c_byte, c_char, Structure, POINTER
    from ctypes.util import find_library

    class c_dir(Structure):
        """Opaque type for directory entries, corresponds to struct DIR"""
        pass

    c_dir_p = POINTER(c_dir)

    class c_dirent(Structure):
        """Directory entry"""
        # FIXME not sure these are the exactly correct types!
        _fields_ = (
            ('d_ino', c_long), # inode number
            ('d_off', c_long), # offset to the next dirent
            ('d_reclen', c_ushort), # length of this record
            ('d_type', c_byte), # type of file; not supported by all file system types
            ('d_name', c_char * 4096) # filename
            )

    c_dirent_p = POINTER(c_dirent)

    c_lib = CDLL(find_library("c"))
    # Extract functions:
    opendir = c_lib.opendir
    opendir.argtypes = [c_char_p]
    opendir.restype = c_dir_p

    readdir = c_lib.readdir
    readdir.argtypes = [c_dir_p]
    readdir.restype = c_dirent_p

    closedir = c_lib.closedir
    closedir.argtypes = [c_dir_p]
    closedir.restype = c_int

    def listdir(path):
        """
        A generator to return the names of files in the directory passed in
        """
        st = os.stat(path) # Raise an error if path doesn't exist or we don't have permission to access it
        # Check if we got a dir or something else!
        # Check gotten from stat.py (for fast checking):
        if (st.st_mode & 0170000) != 0040000:
            e = OSError()
            e.errno = 20; e.filename = path; e.strerror = "Not a directory"
            raise e
        dir_p = opendir(path)
        try:
            while True:
                p = readdir(dir_p)
                if not p: break # End of directory
                name = p.contents.d_name
                if name!="." and name!="..": yield name
        finally: closedir(dir_p)

else:
    print >> sys.stderr, "WARNING: Platform is '"+sys.platform+"'!\nFalling back to os.listdir(), iterator generator will not be returned!"
    listdir = os.listdir

if __name__ == "__main__":
    print
    if len(sys.argv)!=1:
        try: limit = int(sys.argv[2])
        except: limit = -1
        count = 0
        for name in listdir(sys.argv[1]):
            if count==limit: break
            count += 1
            print repr(name),
        print "\nListed", count, "items from directory '%s'" % sys.argv[1]
    if len(sys.argv)!=1: sys.exit()
    from timeit import *
    print "Speed test:"
    dir = ("/etc", r"C:\WINDOWS\system32")[sys.platform.startswith("win")]
    t = Timer("l = listdir(%s)" % repr(dir), "from listdir import listdir")
    print "Measuring time required to create an iterator to list a directory:"
    time = t.timeit(200)
    print "Time required to return a generator for directory '"+dir+"' is", time, "seconds measured through 200 passes"
    t = Timer("l = os.listdir(%s)" % repr(dir), "import os")
    print "Measuring time required to create a list of directory in advance using os.listdir():"
    time = t.timeit(200)
    print "Time required to return a list for directory '"+dir+"' is", time, "seconds measured through 200 passes"
    t = Timer("l = []\nfor file in listdir(%s): l.append(file)" % repr(dir), "from listdir import listdir")
    print "Measuring time needed to create a list of directory using our listdir() instead of os.listdir():"
    time = t.timeit(200)
    print "Time required to create a list for directory '"+dir+"' using our listdir() instead of os.listdir() is", time, "seconds measured through 200 passes"

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 python 从包含数千个文件的目录中复制前 100 个文件? 的相关文章

  • 使用Python开发Web应用程序

    我一直在用 python 做一些工作 但这都是针对独立应用程序的 我很想知道 python 的任何分支是否支持 Web 开发 有人还会建议一个好的教程或网站吗 我可以从中学习一些使用 python 进行 Web 开发的基础知识 既然大家都说
  • 使用 openCV 对图像中的子图像进行通用检测

    免责声明 我是计算机视觉菜鸟 我看过很多关于如何在较大图像中查找特定子图像的堆栈溢出帖子 我的用例有点不同 因为我不希望它是具体的 而且我不确定如何做到这一点 如果可能的话 但我感觉应该如此 我有大量图像数据集 有时 其中一些图像是数据集的
  • 如何生成给定范围内的回文数列表?

    假设范围是 1 X 120 这是我尝试过的 gt gt gt def isPalindrome s check if a number is a Palindrome s str s return s s 1 gt gt gt def ge
  • 如何在android上的python kivy中关闭应用程序后使服务继续工作

    我希望我的服务在关闭应用程序后继续工作 但我做不到 我听说我应该使用startForeground 但如何在Python中做到这一点呢 应用程序代码 from kivy app import App from kivy uix floatl
  • DreamPie 不适用于 Python 3.2

    我最喜欢的 Python shell 是DreamPie http dreampie sourceforge net 我想将它与 Python 3 2 一起使用 我使用了 添加解释器 DreamPie 应用程序并添加了 Python 3 2
  • Spark的distinct()函数是否仅对每个分区中的不同元组进行洗牌

    据我了解 distinct 哈希分区 RDD 来识别唯一键 但它是否针对仅移动每个分区的不同元组进行了优化 想象一个具有以下分区的 RDD 1 2 2 1 4 2 2 1 3 3 5 4 5 5 5 在此 RDD 上的不同键上 所有重复键
  • 在循环中每次迭代开始时将变量重新分配给原始值(在循环之前定义)

    在Python中 你使用 在每次迭代开始时将变量重新分配给原始值 在循环之前定义 时 也就是说 original 1D o o o for i in range 0 3 new original 1D revert back to orig
  • NameError:名称“urllib”未定义”

    CODE import networkx as net from urllib request import urlopen def read lj friends g name fetch the friend list from Liv
  • feedparser 在脚本运行期间失败,但无法在交互式 python 控制台中重现

    当我运行 eclipse 或在 iPython 中运行脚本时 它失败了 ascii codec can t decode byte 0xe2 in position 32 ordinal not in range 128 我不知道为什么 但
  • python pandas 中的双端队列

    我正在使用Python的deque 实现一个简单的循环缓冲区 from collections import deque import numpy as np test sequence np array range 100 2 resha
  • python 集合可以包含的值的数量是否有限制?

    我正在尝试使用 python 设置作为 mysql 表中 ids 的过滤器 python集存储了所有要过滤的id 现在大约有30000个 这个数字会随着时间的推移慢慢增长 我担心python集的最大容量 它可以包含的元素数量有限制吗 您最大
  • 当玩家触摸屏幕一侧时,如何让 pygame 发出警告?

    我使用 pygame 创建了一个游戏 当玩家触摸屏幕一侧时 我想让 pygame 给出类似 你不能触摸屏幕两侧 的错误 我尝试在互联网上搜索 但没有找到任何好的结果 我想过在屏幕外添加一个方块 当玩家触摸该方块时 它会发出警告 但这花了很长
  • HTTPS 代理不适用于 Python 的 requests 模块

    我对 Python 还很陌生 我一直在使用他们的 requests 模块作为 PHP 的 cURL 库的替代品 我的代码如下 import requests import json import os import urllib impor
  • ExpectedFailure 被计为错误而不是通过

    我在用着expectedFailure因为有一个我想记录的错误 我现在无法修复 但想将来再回来解决 我的理解expectedFailure是它会将测试计为通过 但在摘要中表示预期失败的数量为 x 类似于它如何处理跳过的 tets 但是 当我
  • Python - 按月对日期进行分组

    这是一个简单的问题 起初我认为很简单而忽略了它 一个小时过去了 我不太确定 所以 我有一个Python列表datetime对象 我想用图表来表示它们 x 值是年份和月份 y 值是此列表中本月发生的日期对象的数量 也许一个例子可以更好地证明这
  • 从 pygame 获取 numpy 数组

    我想通过 python 访问我的网络摄像头 不幸的是 由于网络摄像头的原因 openCV 无法工作 Pygame camera 使用以下代码就像魅力一样 from pygame import camera display camera in
  • 在Python中重置生成器对象

    我有一个由多个yield 返回的生成器对象 准备调用该生成器是相当耗时的操作 这就是为什么我想多次重复使用生成器 y FunctionWithYield for x in y print x here must be something t
  • 检查所有值是否作为字典中的键存在

    我有一个值列表和一本字典 我想确保列表中的每个值都作为字典中的键存在 目前我正在使用两组来确定字典中是否存在任何值 unmapped set foo set bar keys 有没有更Pythonic的方法来测试这个 感觉有点像黑客 您的方
  • 对输入求 Keras 模型的导数返回全零

    所以我有一个 Keras 模型 我想将模型的梯度应用于其输入 这就是我所做的 import tensorflow as tf from keras models import Sequential from keras layers imp
  • Pandas 与 Numpy 数据帧

    看这几行代码 df2 df copy df2 1 df 1 df 1 values 1 df2 ix 0 0 我们的教练说我们需要使用 values属性来访问底层的 numpy 数组 否则我们的代码将无法工作 我知道 pandas Data

随机推荐

  • perl中与-e和正则表达式匹配的文件名

    我需要检查目录中是否存在文件 文件名的模式如下 d1 d2 d3 abcd 12345 67890 dat 在我的程序中 我将知道文件名abcd 我需要写一个if使用条件 e选项并查找与上面给定模式匹配的文件 您可以使用glob返回名称与模
  • xslt 是将文本转换为 xml 结构的好方法吗?

    我正在尝试找到一个更好的解决方案来将纯文本 但每个字段具有预定义的长度 转换为 xml 例如输入文本可以是 Testuser new york 10018 前 11 个字符表示用户名 接下来的 12 个字符表示城市 接下来的 5 个字符表示
  • 没有主键的实体的 Symfony Doctrine 模型

    我在重建 Web 应用程序时正在使用旧数据库 我想使用 Symfony2 x 它显然将 Doctrine 作为 ORM 我有大约 50 个 mysql 表 它们没有主键 当我尝试生成模型时 它不允许我这样做并抛出 表上没有主键 的异常 我是
  • 如何使用联系人框架获取 iOS 9 中的所有联系人记录

    AddressBook 框架的大部分内容在 iOS 9 中已被弃用 在新的 Contacts 框架中文档仅显示如何获取与a匹配的记录NSPredicate 但是如果我想要怎么办all记录 其他两个答案都只从容器中加载联系人defaultCo
  • TLS 不适用于 Kubernetes 中的负载均衡器后端服务

    我试图通过创建服务类型作为负载均衡器来公开集群中的应用程序 这样做的原因是我希望这个应用程序有一个单独的沟通渠道 我有一个 KOPS 集群 我想使用AWS的网络负载均衡器 以便它获得静态IP 当我创建服务并将端口 80 映射到应用程序运行的
  • laravel 5.5 由于不活动,页面已过期。请刷新并重试

    我是 Laravel 的新手 我有一个我不明白的问题 我的项目中有一个日志表单 我的方法是POST 当我尝试请求时 结果是 由于不活动 该页面已过期 请刷新并尝试 再次 但是如果我将方法更改为GET 效果很好 有人可以告诉我为什么会这样以及
  • 卸载从源代码构建的 python?

    我已经从源代码安装了 python 2 6 后来又错误地从包管理器安装了另一个 python 2 6 我找不到卸载从源代码构建的 python 的方法 这可能 容易吗 运行 ubuntu 10 04 您可以使用 checkinstall 来
  • WPF 工具包 DataGrid 复选框问题

    我真的希望有人能在这里帮助我 我的程序中有一个 DataGrid 它有一个复选框列 DataGrid 的 ItemsSource 是以编程方式加载的 DataSet 当我在 DataGrid 中选择几个项目然后滚动它时 我得到了一些非常奇怪
  • 在 HTML 代码中的何处插入 JavaScript 库和 CSS?

    我对 Web 开发不太陌生 当我在互联网上搜索其他主题时 我看到很多人将流行的 JS 库放在他们网站的不同地方 例如 在 上插入 JS 库非常开始或开始 部分 在加载任何 JS 代码或 CSS 文件之前 例如 在 上插入 JS 库结束了 部
  • 如何为spark-submit添加资源jar?

    我的spark应用程序依赖于adam 2 11 0 20 0 jar 每次我都必须将我的应用程序与adam 2 11 0 20 0 jar打包为fat jar以提交到spark 例如我的fat jar是myApp1 adam 2 11 0
  • 以编程方式运行 MSBuild

    我正在尝试以编程方式执行 MSBuild 但无法执行以下命令 string command string Format C Windows Microsoft NET Framework v4 0 30319 msbuild exe 0 1
  • 如何使用 Jersey 2 测试框架为此类编写单元测试

    我正在尝试为 Rest api 调用编写单元测试 该调用具有 POST 方法 用于使用 Jersey2 将视频文件添加到基于 Web 的应用程序 这是我的类方法的签名 TemplateController java 我想为其编写单元测试 P
  • Hibernate MSSQL datetime2 映射

    我有一个存储过程 它返回数据库中数据类型为 datetime2 Java 文件中数据类型为 Date 的列 当我尝试对从数据库获取的时间调用 getTime 时 它返回 19994321211 毫秒 相当于 IST 2015 年 5 月 4
  • 如何使用 fwrite 将结构写入文件?

    我对 C 很陌生 并且在使用 fwrite 时遇到了麻烦 我正在寻找使用一个包含两个值的结构 struct keyEncode unsigned short key 2 unsigned short encoded 2 然后我在 main
  • 如何使用 Jax-RS 返回 Java List Json

    我想知道如何让方法返回 List 的 JSON 数组 例如 GET Produces application json public List
  • 使用 SQLAlchemy 表达式时 Dask read_sql_table 出错

    我正在尝试将 SQLAlchemy 表达式与 dask 的 read sql table 结合使用 以获取通过连接和过滤几个不同表创建的数据集 这文档表明这应该是可能的 下面的示例不包含任何联接 因为不需要它们来复制问题 我构建连接字符串
  • Facebook JS 影响 IE 中的 CSS/@font-face?

    我似乎注意到 Facebook 的 JS div div 似乎影响了我网站在 IE 中的 CSS 例如 假设标题使用 font1 正文使用 font2 有时 在 IE 中 所有字体都使用 font1 甚至交换 标题使用 font2 正文使用
  • 运行 selenium 时如何将参数传递给 google chrome?

    我希望能够在运行 selenium 时将参数传递给 google chrome 我怎样才能做到这一点 当我运行 selenium 时 我使用 Java 命令 Java jar selenium jar 如何将 no sandbox igno
  • 如何从 iOS 应用程序中将视频上传到 YouTube? [关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心以获得指导 在我的 iOS 应用程序中
  • 如何使用 python 从包含数千个文件的目录中复制前 100 个文件?

    我有一个巨大的目录 并且一直在更新 我试图使用 python 仅列出目录中最新的 100 个文件 我尝试使用 os listdir 但是当目录大小接近 1 00 000 个文件时 listdir 似乎崩溃了 或者我没有等待足够长的时间 我只