Writing a string with comma in one column of CSV file
Solution 1:
write()
is a method associated with an open file object.
writerow()
is a method associated with a csvwriter object.
While your question indicates that you want the outcome to be generated by the write()
function, it is not clear why you feel that you need to use the f.write()
method to do this task. What you are attempting to do is most often handled by the csv.writer()
I will provide some guidance on how to accomplish the outcome using writerow()
just in case it helps you to achieve what seems to be the desired end goal.
import csv
n1 = 'n'
key1 = 'alpha_key,beta_key'
n2 = 42
key2 = 'no_comma_in_this_key'
This creates a filehandle that points toward an open file available for writing on the disk.
f = open('myfile.csv', 'w')
This creates a writer object that can use that file (f) behind the scenes to write lines to the file.
wr = csv.writer(f)
For simplicity, gonna create elements that fit into a row as a pair of strings in a list.
row = [str(n1), str(key1)]
Gonna use the csv writer's innate ability to create rows (with the appropriate quote characters to encapsulate the errant comma).
wr.writerow(row)
We can duplicate those steps with the second set of data to show how it works with keys that don't contain commas.
row = [str(n2), str(key2)]
wr.writerow(row)
When we are done with the file we should close() it, so that any data in the buffer will write to disk (NOTE: a with context manager is better, but for simplicity, going with this approach).
f.close()
The output looks like this and shows how the csv specification handles columns that might contain a comma in them by putting quotes around columns values that have a nested comma.
n,"alpha_key,beta_key"
42,no_comma_in_this_key
Altogether, the code looks like this:
import csv
n1 = 'n'
key1 = 'alpha_key,beta_key'
n2 = 42
key2 = 'no_comma_in_this_key'
f = open('myfile.csv', 'w')
wr = csv.writer(f)
row = [str(n1), str(key1)]
wr.writerow(row)
row = [str(n2), str(key2)]
wr.writerow(row)
f.close()