【问题标题】:Double Quotes at the end of each line while writing from/to .CSV从/向 .CSV 写入时在每行末尾添加双引号
【发布时间】:2012-01-23 18:35:09
【问题描述】:

谁能帮我去掉每行开头/结尾的双引号?

我有一个大的 csv(800k 行)并且想要创建插入语句以将数据导入 SQL DB。我知道代码真的很难看,但我以前从未使用过 Python……非常感谢任何帮助……

#Script file to read from .csv containing raw location data (zip code database)
#SQL insert statements are written to another CSV
#Duplicate zip codes are removed


import csv

Blockquote

csvfile = open('c:\Canada\canada_zip.csv', 'rb')
dialect = csv.Sniffer().sniff(csvfile.readline())
csvfile.seek(0)
reader = csv.reader(csvfile, dialect)
reader.next()

ofile  = open('c:\Canada\canada_inserts.csv', 'wb')
writer = csv.writer(ofile, dialect)

#DROP / CREATE TABLE
createTableCmd = '''DROP TABLE PopulatedPlacesCanada       \n\
CREATE TABLE PopulatedPlacesCanada                         \n\
(                                                  \n\
ID INT primary key identity not null,      \n\
Zip VARCHAR(10),                           \n\
City nVARCHAR(100),                        \n\
County nvarchar(100),                      \n\
StateCode varchar(3),                      \n\
StateName nvarchar(100),                   \n\
Country nvarchar(30),                      \n\
Latitude float,                            \n\
Longitude float,                           \n\
PopulationCount int,                       \n\
Timezone int,                              \n\
Dst  bit                                   \n\
)'''
writer.writerow([createTableCmd])

table = 'PopulatedPlacesCanada'
db_fields = 'Zip, City, County, StateCode, StateName, Country, Latitude, Longitude,         PopulationCount, Timezone, Dst'
zip_codes = set()

count = 0

for row in reader:
  if row[0] not in zip_codes: #only add row if zip code is unique
    count = count + 1
    zipCode = row[0] #not every row in the csv is needed so handpick them using row[n]
    city = row[1].replace("\'", "").strip()
    county = ""
    state_abr = row[2]
    state = row[3].replace("\'", "").strip()
    country = 'Canada'
    lat = row[8]
    lon = row[9]
    pop = row[11]
    timezone = row[6]
    dst = row[7]
    if dst == 'Y':
      dst= '1'
    if dst == 'N':
      dst = '0'
    query = "INSERT INTO {0}({1}) VALUES ('{2}', '{3}', '{4}', '{5}', '{6}', '{7}', {8}, {9}, {10}, {11}, {12})".format(table, db_fields, zipCode, city, county, state_abr, state, country, lat, lon, pop, timezone, dst)
    writer.writerow([query])
    zip_codes.add(row[0])
    if count == 100:  #Go statement to make sql batch size manageable
      writer.writerow(['GO'])

【问题讨论】:

    标签: python sql csv double-quotes


    【解决方案1】:

    2 指针优先:-
    1) 对多行字符串使用三重引号而不是三撇号。
    2) 不需要在多行字符串中加入“\n\”。

    要从一行中删除引号,请使用 python 的正则表达式模块而不是字符串替换。

    import re
    quotes = re.compile('^["\']|["\']$')
    city = quotes.sub( row[3] )
    state = quotes.sub( row[4] )
    

    或者您可以使用 strip 与要从两端删除的字符;一次只有一个字符 AFAIK:-

    city = row[3].strip('"').strip("'")
    state = row[4].strip('"').strip("'")
    

    最后,不要将 csv 模块用于文件输出,因为它需要“上下文”。只需打开文件,然后写入即可。

    ofile = file( 'canada_inserts.sql','w' )
    ofile.write( createTableCmd + '\n' )
    for row in reader:
    ...
       ofile.write( query + '\n' )
    

    【讨论】:

    • 使用replace 恕我直言删除引号没有任何问题。正则表达式在这里实际上是多余的。最后一部分实际上回答了他的问题,但有点间接。
    • replace 没有错,不,但使用它效率低下,因为它搜索行中的每个字符,而不仅仅是开始和结束字符,正如所描述的预期效果。我同意 RE 有点矫枉过正,但是当提前编译时,它们对于重复的文本操作更有效。
    【解决方案2】:

    您不是在编写 CSV 文件。不要为此使用 csv 编写器,因为它可能会为您的数据添加额外的 ascaping。相反,使用

    ofile = file( 'load.sql', 'w')
    # Raw write, no newline added:
    ofile.write(...)
    # or, with newline at the end:
    print >>ofile, "foobar."
    

    是 CSV 编写器在您的行中添加引号:大多数 CSV 方言希望字符串在包含某些字符(例如 ,; 甚至空格)时用引号括起来。但是,由于您编写的是 SQL 而不是 CSV,因此您不需要也不想要这个。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-09
      • 1970-01-01
      • 2017-04-28
      • 2013-01-23
      • 2020-07-13
      • 1970-01-01
      • 2020-02-24
      • 2016-04-13
      相关资源
      最近更新 更多