Home > Software engineering >  creating array with word list and using json to output the array to its own file, I got a attribute
creating array with word list and using json to output the array to its own file, I got a attribute

Time:02-04

I'm working on a bot and to get my word list for it I have to run through the file and make each word a item on the array, and then output it to its own .json file. I came across a attribute error and cant find anything on google about it, Thanks for the help.

CODE:

import json

filename = 'Wordlist.txt'

dict1 = []

a_file = open(filename, "r")

for line in a_file:
    stripped_line=line.strip()
    line_list = stripped_line.split()
    dict1.append(line_list)

a_file.close()
out_file = ("GameWords.json", "w")
json.dump(dict1, out_file, indent=4, sort_keys=False)
out_file.close()

print(dict1)

EROR:

Traceback (most recent call last):
  File "C:/Users/Jacob/AppData/Roaming/JetBrains/PyCharmCE2021.2/scratches/scratch_3.py", line 16, in <module>
    json.dump(dict1, out_file, indent=4, sort_keys=False)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.2800.0_x64__qbz5n2kfra8p0\lib\json\__init__.py", line 180, in dump
    fp.write(chunk)
AttributeError: 'tuple' object has no attribute 'write'

CodePudding user response:

The main problem here is that you haven't opened the file you want to write to. This can be corrected with:

out_file = open("GameWords.json", "w")

To further improve this, you can use the with syntax to elevate having to close the file.

with open("GameWords.json", "w") as out_file:
   json.dump(dict1, out_file, indent=4, sort_keys=False)

See:
https://www.geeksforgeeks.org/with-statement-in-python/

  •  Tags:  
  • Related