Advertisement
furas

Python - JSON

May 21st, 2018
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.00 KB | None | 0 0
  1. ###################################################
  2. #   with JSON
  3. ###################################################
  4.  
  5. import json
  6.  
  7. #--- write ---
  8.  
  9. Var1 = 1
  10. Var2 = 2
  11.  
  12. data = [Var1, Var2]
  13.  
  14. with open("MyFile.txt", "w") as TxtFile:
  15.     json.dump(data, TxtFile)
  16.  
  17. #--- read ---
  18.  
  19. with open("MyFile.txt") as TxtFile:
  20.     data = json.load(TxtFile)
  21.  
  22. Var1 = data[0]
  23. Var2 = data[1]
  24.  
  25. print(Var1, type(Var1)) # 1 <class 'int'>
  26. print(Var2, type(Var2)) # 2 <class 'int'>
  27.  
  28.  
  29. ###################################################
  30. #   without JSON
  31. ###################################################
  32.  
  33. # --- write ---
  34.  
  35. Var1 = 1
  36. Var2 = 2
  37.  
  38. with open("MyFile.txt", "w") as TxtFile:
  39.     TxtFile.write(str(Var1))
  40.     TxtFile.write('\n')
  41.     TxtFile.write(str(Var2))
  42.     TxtFile.write('\n')
  43.  
  44. # --- read ---
  45.  
  46. with open("MyFile.txt") as TxtFile:
  47.     Var1 = int(TxtFile.readline())
  48.     Var2 = int(TxtFile.readline())
  49.  
  50. print(Var1, type(Var1)) # 1 <class 'int'>
  51. print(Var2, type(Var2)) # 2 <class 'int'>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement