Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: write() argument must be str, not dict [duplicate]

Tags:

python

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?

like image 884
charwisc Avatar asked Apr 25 '26 05:04

charwisc


1 Answers

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)
like image 166
KetZoomer Avatar answered Apr 26 '26 19:04

KetZoomer