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
onice
V2EX  ›  Python

Python 中 open 函数的 read(size)方法如何循环

  •  
  •   onice · 2017-11-14 16:56:18 +08:00 · 4135 次点击
    这是一个创建于 2355 天前的主题,其中的信息可能已经有所发展或是发生改变。

    直接调用 read 函数是读取所有文件到内存中。

    但是函数中可以加一个整数,表示从文件中读入多少字节文件。

    如果文件过大,直接用 read 读感觉会撑爆内存。但是用 read(1024)读吧,又要读取多次。肯定要使用循环。

    但是循环该如何写呢?例如下面的例子:

    with open("D:/source.exe", 'rb') as f_in:
    	with open("D:/target.exe", 'wb') as f_out:
        	#使用 read(size)函数希望把 D:/source.txt 复制到 D:/target.exe
    
    第 1 条附言  ·  2017-11-14 17:37:39 +08:00
    感谢各位大大指点。其实 open 打开的文件返回对象是一个可迭代对象,直接用 for 迭代就能处理大文件了。
    参考: https://stackoverflow.com/questions/8009882/how-to-read-large-file-line-by-line-in-python
    6 条回复    2017-11-15 09:47:31 +08:00
    n2ex2
        1
    n2ex2  
       2017-11-14 17:01:43 +08:00 via Android
    .seek()
    Trim21
        2
    Trim21  
       2017-11-14 17:02:39 +08:00
    这个思路不行吗?楼主的疑问是从哪里来的..

    with open('f1') as f_in:
    ....with open('f2') as f_out:
    ........for x in range(1, size_of_f_in, 1024):
    ............content = f_in.read(1024)
    .............append_to_file_out(content)
    Trim21
        3
    Trim21  
       2017-11-14 17:07:51 +08:00   ❤️ 1
    刚刚随手写的,size_of_file_in 随手写一个比 f_in 大的都可以,跑了下 md5 是一样的

    with open('page.db.bak', 'rb') as f_in:
    with open('f2', 'wb') as f_out:
    for x in range(1, 1000000000, 100):
    content = f_in.read(100)
    f_out.write(content)
    cy97cool
        4
    cy97cool  
       2017-11-14 18:43:54 +08:00 via Android
    直接死循环读就行 读到空字符串就 break
    hjuj91
        5
    hjuj91  
       2017-11-14 19:06:47 +08:00
    用 pipe redirect 不行么。。
    NoAnyLove
        6
    NoAnyLove  
       2017-11-15 09:47:31 +08:00
    readline 需要换行符界定一行,如果一行太长了,可以这么做:

    from functools import partial

    with open('1.in', 'rb') as f_in, open('1.out', 'wb') as f_out:
    ....read_iter = iter(partial(f_in.read, 1024), b'')
    ....for block in read_iter:
    ........f_out.write(block)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1095 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 23:19 · PVG 07:19 · LAX 16:19 · JFK 19:19
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.