0

Say i have a notepad file (.txt) with the following content:

"Hello I am really bad at programming"

Using json, how would I get the sentence from the file to the python program which I can then use as a variable?

So far I have this code:

newfile = open((compfilename)+'.txt', 'r')

saveddata = json.load(newfile)

orgsentence = saveddata[0]

I always get this error:

   return codecs.ascii_decode(input, self.errors)[0]
   UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0:           ordinal not in range(128)

Thanks in advance for any help!

Kronixion
  • 11
  • 6

2 Answers2

2

Though you are using txt file. You could read this file without json. But as you mentioned in the question, you can try like this

hello.txt

"Hello I am really bad at programming"

To read this txt file,

import json
from pprint import pprint

with open('hello.txt') as myfile:
    mydata = json.load(myfile) #to load json
    print myfile.read() #to print contents on stdout, not using json load

pprint(mydata)

Output:

u'Hello I am really bad at programming'
manvi77
  • 536
  • 1
  • 5
  • 15
0
import json

with open('file.txt') as f:
    data = json.load(f)
dimmg
  • 3,316
  • 2
  • 20
  • 29