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

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

  •  
  •   lailongmen · 2018-05-20 22:55:06 +08:00 · 2957 次点击
    这是一个创建于 2138 天前的主题,其中的信息可能已经有所发展或是发生改变。
    #这个文档内容是空的。
    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 条回复    2018-05-21 12:27:59 +08:00
    janxin
        1
    janxin  
       2018-05-20 22:56:19 +08:00 via iPad
    因为你用写模式打开的
    lailongmen
        2
    lailongmen  
    OP
       2018-05-20 23:00:39 +08:00
    @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
        3
    manzhiyong  
       2018-05-20 23:09:16 +08:00   ❤️ 1
    py2 可以用 if data == '':
    lailongmen
        4
    lailongmen  
    OP
       2018-05-20 23:11:16 +08:00
    @manzhiyong 谢谢,搞定了。py3 也支持
    maxoxo
        5
    maxoxo  
       2018-05-20 23:14:28 +08:00 via Android   ❤️ 1
    if score1 == bool(False) 为什么不是 if not score1,关于空文件,我没测试啊,不过 Win 下会在保存文件的时候 加入 /r/n 所以,即便是空文件 if not score1 是成立的,最好使用二进制,好像就是 w,打开然后 print score1 看看。
    lailongmen
        6
    lailongmen  
    OP
       2018-05-20 23:17:14 +08:00
    @maxoxo 谢谢,刚测试了,你这个方式也可以。
    janxin
        7
    janxin  
       2018-05-20 23:40:25 +08:00 via iPhone   ❤️ 1
    @lailongmen 是这样会直接清空文件…
    Tink
        8
    Tink  
       2018-05-21 06:43:01 +08:00 via iPhone   ❤️ 1
    本来有内容,你这样打开就没了
    AlisaDestiny
        9
    AlisaDestiny  
       2018-05-21 12:27:59 +08:00   ❤️ 1
    判断文件是否为空最好用文件的 size.我觉得。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5242 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 09:36 · PVG 17:36 · LAX 02:36 · JFK 05:36
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.