2016-10-05 88 views
-1

我有一個csv正在從url中導入並放入數據庫,但是它會導入名稱和id周圍的引號以便將其刪除。 csv文件的原始格式是從python中的csv文件數據中刪除引用

"Apple Inc.",113.08,113.07 
"Alphabet Inc.",777.61,777.30 
"Microsoft Corporation",57.730,57.720 

我現在的代碼如下。

def csv_new(conn, cursor, filename): 
    with open(filename, 'rt') as csv_file: 
     csv_data = csv.reader(csv_file) 
     for row in csv_data: 
      if(not row[0][0].isdigit()): 
       continue 
      split = [int(x) for x in row[0].split('/')] 
      row[0] = datetime.datetime(split[2], split[0], 
             split[1]).date().isoformat() 
      print(row); 
      cursor.execute('INSERT INTO `trade_data`.`import_data`' 
          '(date, name, price) VALUES(%s, "%s", %s)', 
          row) 
    conn.commit() 

最終數據庫看起來像這樣

Name | Price1| Price 2| 
'Apple Inc.' 113.08 113.07 
'Alphabet Inc.' 777.61 777.30 
'Microsoft Corporation' 57.730 57.720 

,我想它看起來像

Name | Price1| Price 2| 
Apple Inc. 113.08 113.07 
Alphabet Inc. 777.61 777.30 
Microsoft Corporation 57.730 57.720 

我csv.reader使用行(new_data.splitlines試過() delimiter =',skipinitialspace = True):但它拋出錯誤

+0

該代碼有太多的錯誤來弄清楚發生了什麼。如何讀取csv並打印通常添加到數據庫的工作示例? – tdelaney

+0

如何從數據庫中打印數據?該字段是否真的有引號,或者我們剛剛看到引用的字符串數據呈現?例如,在python中,如果print('(「Apple Inc.」,113.08,113.07)')'我得到包含引號的字符串repl,即使它們不在字符串本身中('(「Apple Inc. 「,113.08,113.07)')。 – tdelaney

+0

該字符串引號即時通訊不打印在python im導入到sql數據庫。 – user3170242

回答

0

想通了,是因爲tdelaney提到的問題是,沒有引號的話acually這是蟒蛇在字符串中,所以我在

cursor.execute('INSERT INTO `trade_data`.`import_data`' 
         '(date, name, price) VALUES(%s, "%s", %s)', 
         row) 

到%s,而不是「%變化值s「它解決了問題並刪除了額外的引號。

1

csv.reader正確刪除引號。您可能正在查看文本的帶引號的字符串表示形式,而不是實際的文本。

>>> new_data = '''"Apple Inc.",113.08,113.07 
... "Alphabet Inc.",777.61,777.30 
... "Microsoft Corporation",57.730,57.720''' 
>>> 
>>> import csv 
>>> 
>>> for row in csv.reader(new_data.splitlines()): 
...  print(','.join(row)) 
... 
Apple Inc.,113.08,113.07 
Alphabet Inc.,777.61,777.30 
Microsoft Corporation,57.730,57.720 
>>> 
+0

問題出現在我將它導入到SQL時,它周圍有引號。 – user3170242