写入/读取.CSV时每行末尾的双引号
有没有人能帮我去掉每行开头和结尾的双引号?
我有一个很大的csv文件(有80万行),想要创建插入语句把数据放进SQL数据库里。我知道我的代码写得很糟糕,但我之前从来没用过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'])
2 个回答
0
先说说两个指针的用法:
1) 对于多行字符串,使用三重反引号比三重单引号更好。
2) 在多行字符串中,不需要加“\n”来换行。
如果想要去掉一行中的引号,可以用Python的正则表达式模块,而不是用字符串替换。
import re
quotes = re.compile('^["\']|["\']$')
city = quotes.sub( row[3] )
state = quotes.sub( row[4] )
或者你可以用strip方法,去掉你想要从两端去掉的字符;不过我知道的只支持一次去掉一个字符:-
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' )
0
你并不是在写一个CSV文件。所以不要用CSV写入工具,因为它可能会给你的数据添加额外的转义字符。相反,你应该使用
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,所以你不需要也不想要这些引号。