推荐学习书目
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
sjmcefc2
V2EX  ›  Python

求教 Python 读文件,每次读 1w 行,有没有可以直接用的函数呢?

  •  
  •   sjmcefc2 · Jul 25, 2018 · 3802 views
    This topic created in 2850 days ago, the information mentioned may be changed or developed.

    用了 readlines ( 10000 ) Returns the next 10000 bytes of line. Only complete lines will be returned. 有没有可以直接用的函数呢?可以顺序每次读 1w 行,最后不足 1w 也能正常返回?

    10 replies    2018-07-25 11:34:42 +08:00
    sjmcefc2
        2
    sjmcefc2  
    OP
       Jul 25, 2018
    @noqwerty 非常感谢。请教如何才能找到自己需要的轮子呢。这个太棒了。
    noqwerty
        3
    noqwerty  
       Jul 25, 2018
    @sjmcefc2 #2 善用 Google 和 StackOverflow 呗,我觉得我这半桶水能问出来的问题基本都是别人问过的……
    luzhongqiu
        4
    luzhongqiu  
       Jul 25, 2018
    建议迭代器返回,上限用参数传过去不就好了么-。-
    qsnow6
        5
    qsnow6  
       Jul 25, 2018
    linecache 模块了解下
    wwwyiqiao
        6
    wwwyiqiao  
       Jul 25, 2018
    自己封装一个呀
    huahuajun9527
        7
    huahuajun9527  
       Jul 25, 2018
    ```python
    def rows_reader(filepath, size=10):
    with open(filepath) as f:
    tmp = []
    for line in f:
    tmp.append(line)
    if len(tmp) >= size:
    yield tmp
    tmp = []
    if tmp:
    yield tmp


    for rows in rows_reader('m.md', size=10):
    print(rows)

    ```
    necomancer
        8
    necomancer  
       Jul 25, 2018
    要是读数据的话可以试试 pandas
    import pandas as pd
    f = pd.read_csv(<file_name>, chunksize =10000, ...)
    更多参数看 https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html
    然后
    for chunk in f:
    do_sth(chunk)
    sjmcefc2
        9
    sjmcefc2  
    OP
       Jul 25, 2018
    @wwwyiqiao 觉得还是站在各位巨人肩膀上更好。
    sjmcefc2
        10
    sjmcefc2  
    OP
       Jul 25, 2018
    @luzhongqiu 不知道每个文件有多少行啊,迭代器我再学习下。

    @necomancer 非常感谢。不过我这个是个 txt,要按照行来读取。

    @huahuajun9527 这个太棒了我,试一下。
    另外大家都怎么找到这些常用的模块,而不用自己封装一个呢?当然,高手,封装一个也是一秒钟的事儿。现成的模块对我这种外行来说,如何找到呢?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   936 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 772ms · UTC 19:30 · PVG 03:30 · LAX 12:30 · JFK 15:30
    ♥ Do have faith in what you're doing.