When I try to write a dict to a file like so (list here is a list of dicts):
for x in range(len(list)):
outfile = open('message.txt', 'w')
outfile.write(list[x])
outfile.close()
I get an error that says TypeError: write() argument must be str, not dict. How can I fix this?
You can't write a dictionary to a file, as the file.write method expects a string. Instead, you can use either use print(..., file=file_object) or file.write(str(...)).
Code:
outfile = open("message.txt", "w")
for index in range(len(input_list)):
print(input_list[index], file=outfile)
outfile.close()
Furthermore, you can directly iterate over the list and use the with statement to open the file:
for item in input_list:
with open("message.txt", "w") as outfile:
print(item, file=outfile)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With