简体   繁体   English

来自文件的Python 3 read()不适用于1个字节的文件

[英]Python 3 read() from file doesn't work with 1 byte files

I'm trying to read a simple value from a file like this: 我试图从这样的文件中读取一个简单的值:

import pdb
import string

def getOrderID():
    f = open( 'testid.txt', 'w+')
    tmp = f.read()
    print( 'tmp: ', tmp, len(tmp) )
    if tmp.isdigit():
        newid = int(newid) + 1
    else:
        newid = 1

    print( 'Newid: ', newid )

    f.seek(0)
    f.write(str(newid))
    f.close()

    return newid

print( getOrderID() )

tmp is always an empty string, size 0 tmp始终为空字符串,大小为0

newid is always 1. Why? newid总是1.为什么?

Description of the w+ mode: Open for reading and writing. w+模式的描述:打开以进行读写。 The file is created if it does not exist, otherwise it is truncated. 如果文件不存在,则创建该文件,否则将被截断。 The stream is positioned at the beginning of the file. 流位于文件的开头。

That's why the string is empty and newid is 1. 这就是字符串为空且newid为1的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM