V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
dbj1991
V2EX  ›  Python

一个文件夹下有百万个文件,怎么读取?

  •  
  •   dbj1991 · 2017-05-05 19:45:10 +08:00 · 5186 次点击
    这是一个创建于 2540 天前的主题,其中的信息可能已经有所发展或是发生改变。
    之前把爬虫爬取的源文件都存在了一个文件夹,有一百多万个,现在要读取,直接用 os.walk(path) 这种方式,几个小时了还卡在这一步,有没有其他的方式可以快速的读取
    14 条回复    2017-06-01 01:43:26 +08:00
    cheneydog
        1
    cheneydog  
       2017-05-05 19:52:58 +08:00   ❤️ 1
    ls /xxx >list
    sheep3
        2
    sheep3  
       2017-05-05 19:55:13 +08:00
    ```
    import subprocess
    cat = subprocess.Popen(["ll",], stdout=subprocess.PIPE)
    for line in cat.stdout:
    print line
    ```
    dsg001
        3
    dsg001  
       2017-05-05 20:24:59 +08:00
    ```
    import glob
    for file in glob.iglob('path'):
    print(file)
    '''
    minbaby
        4
    minbaby  
       2017-05-05 20:35:26 +08:00
    一看楼上就是没有遇到过几百万文件在一个目录的情况,之前遇到过(因为 crontab 用了 wget 导致的),用 ls 命令已经不好使了,这个时候只能通过文件名字的规律来处理了,比如文件名是五位数字,可以试试 ls 11* 这种方式缩小每次读取的文件数量
    rrfeng
        5
    rrfeng  
       2017-05-05 20:38:43 +08:00   ❤️ 1
    ls -U
    Osk
        6
    Osk  
       2017-05-05 21:40:31 +08:00   ❤️ 2
    $ time ls -U | wc -l
    5973243

    real 0m2.330s
    user 0m1.743s
    sys 0m0.790s

    不用-U 要 24 秒多
    privil
        7
    privil  
       2017-05-05 21:46:47 +08:00
    @Osk 正解,U 参数!我用 ls -U 删了两千万文件……
    Ouyangan
        8
    Ouyangan  
       2017-05-05 21:55:18 +08:00
    100 万 , 真刺激
    lxf1992521
        9
    lxf1992521  
       2017-05-05 22:07:10 +08:00
    find > a 生成索引,在使用 python 去处理一个几百万行的文本即可。
    dbj1991
        10
    dbj1991  
    OP
       2017-05-06 06:59:21 +08:00
    @Osk @minbaby @lxf1992521 那如果是在 windows 下呢
    minbaby
        11
    minbaby  
       2017-05-06 14:14:01 +08:00
    @dbj1991 win 下就不知道了,没经历过
    ihciah
        12
    ihciah  
       2017-05-06 22:03:06 +08:00
    想起某童鞋经历过的 inode 用完的情况。。。。
    beordle
        13
    beordle  
       2017-05-07 00:57:39 +08:00
    @Osk 学习了
    HMSQQbA
        14
    HMSQQbA  
       2017-06-01 01:43:26 +08:00 via Android
    @cheneydog 这样会多出一项
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3647 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 04:31 · PVG 12:31 · LAX 21:31 · JFK 00:31
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.