klammerauf
klammerauf

Reputation: 17

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

newid is always 1. Why?

Upvotes: 1

Views: 84

Answers (1)

Jayanth Koushik
Jayanth Koushik

Reputation: 9904

Description of the w+ mode: Open for reading and writing. 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.

Upvotes: 3

Related Questions