在csv文件中保存长字符串

时间:2015-11-19 19:45:18

标签: python csv

我的字符串如下:

str1 = "1 2 1 ... 1 2 2, 2 2 1 ... 1 1 2" # The ellipses(...) are just for representing that the string is very long.

我将它保存在这样的csv文件中:

myFile = open('file.csv','w')
myFile.write('CellA, CellB') # "CellA" and "CellB" are stored in separated cells
myFile.write('\n')
myFile.write(str1) # Parts(not char by char) of str1 are stored in multiple cells but the string appears to be written perfectly in Notepad++.
myFile.write('\n')
myFile.close()

我能够做到这一点:

CellA CellB   # Where CellA and CellB are written in two separate cells

我希望str1字符串以类似的方式存储,','作为分隔符,如:

1 2 1 ... 1 2 2    2 2 1 ... 1 1 2 # '1 2 1 ... 1 2 2' and '2 2 1 ... 1 1 2' should be stored in two separate cells.

此方法适用于CellA,CellB'但不是str1。为什么这样,我该如何解决这个问题?

修改 实际字符串很长:https://docs.google.com/document/d/1X0SHwBFlZNcFGw4jbdRAF-MY2D5YV-syRYbbU2J1zpc/edit?usp=sharing

1 个答案:

答案 0 :(得分:1)

您是否尝试过使用python的csv模块?

例如:

import csv
with open('eggs.csv', 'wb') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=' ',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
    spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])

来自Python csv library