Akshay Nagpal
Akshay Nagpal

Reputation: 97

JSON File I/O : Extra Data Error

I am learning Python currently. For a small project, I am writing a script to dump and load JSON extracted from the web. The file needs to be constantly updated after pulling the data each time and for the same, I have written the following code.

    with open(os.path.join(d,fname),'a+') as f:
        try:
            f.seek(0)
            t = json.load(f)
            for i in t:
                tmp[i]=t[i]
        except Exception as e:
            print(e,"New File ",fname," is created in ",d)
        f.truncate()
        json.dump(tmp,f)

I have put a try-catch block since the first time this program runs, the file would have no data written.

When I run the script, it works as expected but when I run the same script the fourth time, it gives EXTRA DATA exception.

Extra data: line 1 column 29245 (char 29244) New File TSLA_dann is created in 2017-12-20

I am not sure how another dictionary is being written in the file. Please guide me to the same.

Upvotes: 1

Views: 378

Answers (1)

Chameleon
Chameleon

Reputation: 10128

It is nearly impossible to write another json with such code. Your code is not good. You mix too much try open, seek and truncate, wrong file mode choice maybe. I will teach you little to be much better:

  1. try should cover only what can raise error.
  2. Seek is not need always seek(0) is after open.
  3. open(x, 'a+) mean append to the end I think (i can be reason of error).
  4. use spaces.
  5. be patient.

Problem is probably 'a+' mode but it is not matter clean the code :)

Believe me I writing 250 000 line programs without problems.

Clean code for you as good example should work (I was not tested - you can fix it if one letter missed or just run):

# read
file_path = os.path.join(d, fname)
with open(file_path, 'r') as f: # 'r' is read can be skipped
    try:
        t = json.load(f)
    except Exception as e:
        print('%s %s' % (e, file_path))

for i in t:
    tmp[i] = t[i]

# write
with open(file_path, 'w') as f:
    json.dump(tmp, f)        

Upvotes: 1

Related Questions