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

python 中文件打开模式求解?

  •  
  •   import111111 · 2016-03-19 10:54:40 +08:00 · 1886 次点击
    这是一个创建于 2965 天前的主题,其中的信息可能已经有所发展或是发生改变。
    python 中打开一个自定义的日志文件,此文件设定了大小限制。
    要求:
    当写入的数据大于此限制时,从文件开头开始覆盖原记录(每行记录长度相等),那么应该以什么模式打开此文件,才能做到:
    a. 如果没有此文件则新建;
    b. 如果有,不清空原文件。文件大小小于限制时,在文件末尾处添加;
    c . 如果有且大小超过其限制时,不清空原文件并在文件开始处覆盖原记录?

    代码示例:
    with open('test.txt','w+') as f: # w+ 在打开文件时会清空原文件
    f.seek(0)
    i,j = 0,100
    stand = '中华人民共和国:{:10d}\n' # 确保每个记录长度一致
    while i < j:
    f.write(stand.format(i))
    i += 1
    if f.tell() >= 128:
    f.seek(0)
    7 条回复    2016-03-24 10:16:33 +08:00
    import111111
        1
    import111111  
    OP
       2016-03-20 11:12:45 +08:00
    消灭零回复:
    import111111
        2
    import111111  
    OP
       2016-03-20 11:13:50 +08:00
    消灭零回复:
    难道要将文件打开后复制数据再删除再重新创建 a+?
    import111111
        3
    import111111  
    OP
       2016-03-22 10:50:02 +08:00
    !
    billgreen1
        4
    billgreen1  
       2016-03-24 00:23:54 +08:00
    可不可以这样:打开文件,读取内容,存到指定长度的 deque ,以后有新数据就往 deque 里面存,最后写入文件,关闭文件。
    import111111
        5
    import111111  
    OP
       2016-03-24 10:15:06 +08:00
    os.fdopen(os.open('/tmp/nn', os.O_CREAT | os.O_WRONLY), 'w')
    import111111
        6
    import111111  
    OP
       2016-03-24 10:15:50 +08:00
    model = 'r+' if os.path.exists(path) else 'w+'
    with open (path,model) as f: pass
    import111111
        7
    import111111  
    OP
       2016-03-24 10:16:33 +08:00
    model = 'r+' if os.path.exists(path) else 'w+'
    with open (path,model) as f: pass
    @import111111
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2145 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 10:55 · PVG 18:55 · LAX 03:55 · JFK 06:55
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.