Why does file.read() return '' in python

Question:

I am making a blockchain, I am storing the latest block in a file named lb.store
,but my code to open and read the file returns ''.

Here is the Error.

Traceback (most recent call last):
  File "C:UsersShayanNewDocumentsprogrammingPythonBlockchainNodenode.py", line 48, in <module>
    recieve_request()
  File "C:UsersShayanNewDocumentsprogrammingPythonBlockchainNodenode.py", line 39, in recieve_request
    add_block(data)
  File "C:UsersShayanNewDocumentsprogrammingPythonBlockchainNodenode.py", line 7, in add_block
    new_block_number = int(lblock_number) + 1
ValueError: invalid literal for int() with base 10: ''

Here is the full code that caused this:

lblock_numberf = open("lb.store","a+")
    lblock_number = lblock_numberf.read()
    lblock_numberf.close()
    new_block_number = int(lblock_number) + 1
Asked By: shayan bahrainy

||

Answers:

It looks like that the file you’re trying to read is either empty or the end of the string appears to be <"">. Play around the values to debug the problem

Answered By: IuryB

Opening in A+ mode means the cursor is at the end of the file, ready to append. Fix this by opening in read mode; the default.

lblock_numberf = open("lb.store")
lblock_number = lblock_numberf.read()
lblock_numberf.close()
new_block_number = int(lblock_number) + 1
Answered By: shayan bahrainy
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.