使用单词列表创建数组并使用 json 将数组输出到它自己的文件,我遇到了一个我无法弄清楚的属性错误

creating array with word list and using json to output the array to its own file, I got a attribute error I cant figure out

我正在开发一个机器人并为其获取我的单词列表,我必须 运行 通过文件并使每个单词成为数组中的一个项目,然后将其输出到它自己的 .json 文件。我遇到了一个属性错误,在 google 上找不到任何相关信息,感谢您的帮助。

代码:

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)

错误:

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'

这里的主要问题是您还没有打开要写入的文件。这可以通过以下方式更正:

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

为了进一步改善这一点,您可以使用 with 语法来提升关闭文件的必要性。

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

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