正如我在评论中非正式地建议的那样,唯一意味着您需要使用一些不会出现在数据中的字符 -chr(255)
可能是一个不错的选择。例如:
Note:显示的代码适用于 Python 2.x — 请参阅 Python 3 版本的注释。
import csv
DELIMITER = chr(255)
data = ["itemA", "itemB", "itemC",
"Sentence that might contain commas, colons: or even \"quotes\"."]
with open('data.csv', 'wb') as outfile:
writer = csv.writer(outfile, delimiter=DELIMITER)
writer.writerow(data)
with open('data.csv', 'rb') as infile:
reader = csv.reader(infile, delimiter=DELIMITER)
for row in reader:
print row
Output:
['itemA', 'itemB', 'itemC', 'Sentence that might contain commas, colons: or even "quotes".']
如果您不使用csv
模块,而不是手动写入和/或读取数据,那么它会像这样:
with open('data.csv', 'wb') as outfile:
outfile.write(DELIMITER.join(data) + '\n')
with open('data.csv', 'rb') as infile:
row = infile.readline().rstrip().split(DELIMITER)
print row