2017-05-24 69 views
1

我創建一個Django應用程序,我需要導入幾個*.csv文件。 一個人的這個文件具有這樣的結構:Django導入CSV與回車

id|value (header) 

12|¤this is the 

value¤ 

34|¤this is another 

value¤ 

我用這個代碼解析文件:

try: 
    csvfile = open(path, "r", encoding='utf-16') 
except IOError: 
    return False 
cursor.copy_from(csvfile , tblname, columns=['id', 'value'], sep='|') 

但是當我嘗試解析這個文件,它給了我這個錯誤:

psycopg2.DataError: ERROR: missing data for the column "value" 

有沒有辦法解析這個文件,在文本標識符('¤')內保持回車?

回答

0

您可以使用Pythons csv模塊閱讀該模塊。

import csv 

try: 
    csvfile = open(path, newline='') 
except IOError: 
    return False 

csvreader = csv.reader(csvfile, delimiter='|', quotechar='¤') 
for row in csvreader: 
    print(', '.join(row)) # or do something else with the row of data. 
+0

你有幾個選擇這裏爲:

blocks = [] block = [] with open('input.csv') as f_input: for row in f_input: if '|' in row: if len(block): blocks.append(''.join(block).strip('\n').split('|')) block = [] block.append(row) else: block.append(row) if len(block): blocks.append(''.join(block).strip('\n').split('|')) print(blocks) 

如下這將產生塊的列表我看到了。無論是使用'copy_expert'逐行寫入或使用這裏使用的方法http://bonesmoses.org/2014/07/25/friends-dont-let-friends-use-loops/ – hanshoi

+0

不是很優雅,但我創建這個: 嘗試: csvfile =開(路徑,換行= '') 除了IO錯誤: 返回False csvreader = csv.reader(csvfile,分隔符= '|',quotechar = '¤') 在csvreader行: cursor.execute(INSERT INTO「+ table_name +」(id,value)VALUES(''+ row [0] +「','」+ row [1] +「')」) 至少有效 –

0

一個辦法是建立條目自己如下:

[['id', 'value (header)'], ['12', '¤this is the\nvalue¤'], ['34', '¤this is another\nvalue¤']]