2015-11-19 64 views
0

我有串狀:保存在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

+0

你確定字串可是沒有任何其他的逗號? –

+0

@RNar完全確定。我可以提供實際的字符串。 –

+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

+1

是的,但我不明白爲什麼這種方法不起作用。 「CellA」和「CellB」完美地存儲在兩個單獨的單元中,但str1並非如此。 –

+0

你確定它不是由引號引起的問題嗎? @BlackDragon – Veltro

+0

你能告訴我這裏的「引號」是什麼意思嗎? @Liam –