0

I am writing a code to analyze a JSON file. And I want my output as a txt file. The code is as follows..

inputFile = "C:\Users\nk\Documents\survey\data.json"
outfile= "C:\Users\nk\Documents\survey\data_summary.txt"
json_file = open(inputFile, 'r', encoding="utf8")
jsondb = json.load(json_file)

fs = open(outFile, 'w')

#some loops in between

fs.flush()
fs.close()

after running this code in jupyter notebook, it is showing error like

inputFile = "C:\Users\nk\Documents\survey\data.json"              ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escap

What to do ? and how to write??? I am new to programming.

Charnel
  • 4,222
  • 2
  • 16
  • 28
  • How is `typescript` relevant? – VLAZ Jan 23 '20 at 17:48
  • 2
    Is the file valid json? – scottsaenz Jan 23 '20 at 17:50
  • Oh, and this is a duplicate of https://stackoverflow.com/q/37400974/11301900 and https://stackoverflow.com/q/1347791/11301900. – AMC Jan 23 '20 at 23:36
  • Does this answer your question? [(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape](https://stackoverflow.com/questions/37400974/unicode-error-unicodeescape-codec-cant-decode-bytes-in-position-2-3-trunca) – Robert Jan 24 '20 at 01:17

3 Answers3

2

Possibly this is the problem with your file path. Try to change it in this way:

inputFile = r"C:\Users\nk\Documents\survey\data.json"
outfile= r"C:\Users\nk\Documents\survey\data_summary.txt"

This answer might be helpful.

Charnel
  • 4,222
  • 2
  • 16
  • 28
1

You can use either of the below 3 way to represent you file path correctly:

1) inputFile = "C:/Users/nk/Documents/survey/data.json"
   outfile= "C:/Users/nk/Documents/survey/data_summary.txt"

2) inputFile = "C:\\Users\\nk\\Documents\\survey\\data.json"
   outfile= "C:\\Users\\nk\\Documents\\survey\\data_summary.txt"

or as Charnel pointed out:

3) inputFile = r"C:\Users\nk\Documents\survey\data.json"
   outfile= r"C:\Users\nk\Documents\survey\data_summary.txt"
SKS
  • 46
  • 5
0

When typing filenames you used the escape symbol \ as an ordinary one. You have three options to avoid this error.

  1. Change path delimiters using Unix-style C:/Users it works
  2. Type every escape symbol twice C:\\Users
  3. Use special prefix r before string r"C:\Users"

If you wish to understand more details about the error description you can read this answer

Unicode Error ”unicodeescape" codec can't decode bytes… Cannot open text files in Python 3

Sergey
  • 522
  • 2
  • 8