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

新手求教, py3 从一个空文件中读取内容,要如何做判断才对?

  •  
  •   lailongmen · May 20, 2018 · 4154 views
    This topic created in 3093 days ago, the information mentioned may be changed or developed.
    #这个文档内容是空的。
    f=open('C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36-32\\my\\game.txt','w+')
    score1=f.read()
    f.close()

    #下面这个判断怎么都不生效。本意是想当文件内容为空,就写入内容。none 也实验了,没用。
    if score1==bool(False):
    f = open('C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36-32\\my\\game.txt', 'w+')
    f.write('0 0 0')
    f.close()
    9 replies  •  2018-05-21 12:27:59 +08:00
    janxin
    janxin
    May 20, 2018 via iPad
    1
    因为你用写模式打开的
    lailongmen
    lailongmen
    OP
    May 20, 2018
    2
    @janxin 我看了这个文档,是说 w+读写都可以? http://www.runoob.com/python/python-func-open.html
    而且就算我改成 r+,也还是无效。

    f = open('C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36-32\\my\\game.txt', 'r+')
    score1=f.read()
    f.close()
    if score1==bool(False):
    f = open('C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36-32\\my\\game.txt', 'w+')
    f.write('0 0 0')
    f.close()
    manzhiyong
    manzhiyong
    May 20, 2018❤️1
    3
    py2 可以用 if data == '':
    lailongmen
    lailongmen
    OP
    May 20, 2018
    4
    @manzhiyong 谢谢,搞定了。py3 也支持
    maxoxo
    maxoxo
    May 20, 2018 via Android❤️1
    5
    if score1 == bool(False) 为什么不是 if not score1,关于空文件,我没测试啊,不过 Win 下会在保存文件的时候 加入 /r/n 所以,即便是空文件 if not score1 是成立的,最好使用二进制,好像就是 w,打开然后 print score1 看看。
    lailongmen
    lailongmen
    OP
    May 20, 2018
    6
    @maxoxo 谢谢,刚测试了,你这个方式也可以。
    janxin
    janxin
    May 20, 2018 via iPhone❤️1
    7
    @lailongmen 是这样会直接清空文件…
    Tink
    Tink
    May 21, 2018 via iPhone❤️1
    8
    本来有内容,你这样打开就没了
    AlisaDestiny
    AlisaDestiny
    May 21, 2018❤️1
    9
    判断文件是否为空最好用文件的 size.我觉得。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   731 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 22:48 · PVG 06:48 · LAX 14:48 · JFK 17:48
    ♥ Do have faith in what you're doing.