Reputation: 18527
Is it possible to merging the following two statements into one statement?
f.write(",".join(str(cell) for cell in row))
f.write("\n")
Upvotes: 1
Views: 140
Reputation: 4592
Alternatively, you can do with my wrapper library pyexcel
:
import pyexcel
rows = [['foo', 1, 2], ['bar', 3, 4]]
w = pyexcel.Writer("file.csv")
w.write_rows(rows)
w.close()
And the documentation is here
Upvotes: 0
Reputation: 87134
Use string formating:
f.write("{}\n".format(",".join(str(cell) for cell in row)))
Note that this is significantly slower than most other methods, including the two separate writes as per the OP, and the older (deprecated) style of string formatting (e.g. f.write("%s\n", ...)
.
See str.format()
and Format String Syntax.
Upvotes: 2
Reputation: 122116
Why reinvent the wheel? The csv
module will do this for you:
import csv
rows = [['foo', 1, 2], ['bar', 3, 4]]
with open("filename.csv", "w") as f:
writer = csv.writer(f)
writer.writerows(rows)
Upvotes: 1
Reputation: 117981
Just concatenate the result of join
with the '\n'
f.write(",".join(str(cell) for cell in row) + '\n')
Upvotes: 2