简体   繁体   中英

Writing a string with comma in one column of CSV file

I use the following line to write some information to a CSV file which is comma delimited.

f = open(output_file, 'w', newline='')
wr = csv.writer(f)
...
f.write(str(n) + "," + str(key) + "\n" )

Problem is that key is a string which may contain ',' and this causes the final CSV file to have more than 2 columns, while I want to write the whole key as a single column.

I know that wr.writerow([key]) writes the entire key in one column, but I would like to do the same with write() . Any idea to fix that?

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM