【问题标题】:remove quotes from csv file data in python从python中的csv文件数据中删除引号
【发布时间】:2017-02-14 09:22:23
【问题描述】:

我有一个从 url 导入并放入数据库的 csv,但是它在名称和 id 周围使用引号导入,喜欢删除它们。 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) 中使用 for row:但它抛出了错误

【问题讨论】:

  • 该代码有太多错误,无法弄清楚发生了什么。一个读取 csv 然后打印您通常会添加到数据库中的内容的工作示例怎么样?
  • 如何打印数据库中的数据?该字段是否真的有引号,或者我们只是看到数据的带引号的字符串呈现?例如,在 python 中,如果我 print('("Apple Inc.", 113.08, 113.07)') 我得到包含引号的字符串 repl,即使它们不在字符串本身 (("Apple Inc.", 113.08, 113.07)) 中。
  • 字符串有引号,我没有在 python 中打印,我将它们导入 sql 数据库。
  • 编辑使用工作代码

标签: python mysql csv


【解决方案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
>>> 

【讨论】:

  • 当我将它导入到 SQL 时出现问题,它周围有引号。
【解决方案2】:

想通了,问题出在 tdelaney 提到的字符串中不是引号,它是 python,所以我在

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

到 %s 而不是 "%s" 它解决了问题并删除了多余的引号。

【讨论】:

    猜你喜欢
    • 2014-05-05
    • 1970-01-01
    • 2020-03-14
    • 2014-02-24
    • 2019-07-08
    • 1970-01-01
    • 2022-01-20
    • 2016-05-10
    相关资源
    最近更新 更多