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

Python 保存数据为多个文本, 1 个文本仅保存 1 万行数据,如何实现?

  •  
  •   KhadainJHIN · 2017-07-03 17:19:15 +08:00 · 2421 次点击
    这是一个创建于 2483 天前的主题,其中的信息可能已经有所发展或是发生改变。
    将服务器返回的数据保存到本地文本,需要实现的功能如标题:,自动命名文本文件:save1,save2···
    8 条回复    2017-07-04 00:18:37 +08:00
    crazycabbage
        1
    crazycabbage  
       2017-07-03 17:45:42 +08:00   ❤️ 1
    一个变量 count 计数

    ```
    name = 0
    for i in data:
    if count == 10000:
    count = 0
    name += 1
    file_object = open('save%d.txt'%name, 'w+')
    file_object.write(i)
    file_object.close( )
    ```
    knightdf
        2
    knightdf  
       2017-07-03 17:54:05 +08:00   ❤️ 1
    `man split`, 不谢
    KhadainJHIN
        3
    KhadainJHIN  
    OP
       2017-07-03 17:56:40 +08:00
    @crazycabbage 非常感谢提供的思路和代码,我在实际代码中遇到了一个问题:服务器返回的数据长短不一,当存储数据足够 10000 时,才保存为文本,命名为 save1,当存储足够第二个 10000 时,才保存为 save2,如何才能保证检测到这一变化?
    KhadainJHIN
        4
    KhadainJHIN  
    OP
       2017-07-03 17:57:52 +08:00
    @knightdf 😆谢谢,如何检测服务器返回的数据长度呢,要保证这一长度足够才划分文件
    wlsnx
        5
    wlsnx  
       2017-07-03 18:06:23 +08:00
    data = []
    while True:
    r = receive()
    data.extend(r.splitlines())
    if len(data) >= 10000:
    save(data[:10000])
    data = data[10000:]
    KhadainJHIN
        6
    KhadainJHIN  
    OP
       2017-07-03 18:06:37 +08:00
    @knightdf windows 机器···
    romanticbao
        7
    romanticbao  
       2017-07-03 18:47:28 +08:00
    @KhadainJHIN cygwin
    troywinter
        8
    troywinter  
       2017-07-04 00:18:37 +08:00
    你需要的是 file rotation,可以谷歌一下 python 里的 rotatingfilehandler, 参考一下它们标准库里的实现。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2685 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 10:17 · PVG 18:17 · LAX 03:17 · JFK 06:17
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.