I have the following code:
for node, value in sorted(d.iteritems()):
outfile.write([node] + value)
print(node, value)
I read a few different SO posts about this and am still somewhat confused. The print statement works perfectly, printing the key and value correctly in the interpreter. But I couldn’t figure out a way to get the outfile.write() statement to work here. Would greatly appreciate any clarification!
printautomatically converts the given variable to a string (using the__repr__method).file.writedoes not. You could still write to a file with something like:(I also added a newline). However, you don’t make clear in the question what the types of
nodeandvalueare. The expression[node] + valueimplies thatvalueis a list. If you want the list to be comma separated (as implied by your question’s title) you can combine them and join them with commas like so: