【发布时间】:2018-09-27 23:17:37
【问题描述】:
- 使用 Python 2.7.6
- 需要不使用 Pandas 库的解决方案
我的 .csv 文件具有特定(文本)列,其单元格偶尔会包含双引号 (")。在 ArcMap 中转换为 shapefile 时,这些单双引号会导致错误转换。它们必须“转义” .
我需要一个脚本来编辑 .csv 以便它:
- 将“”的所有实例替换为“”。
- 用双引号将每个单元格括起来。
我的脚本:
import csv
with open(Source_CSV, 'r') as file1, open('OUTPUT2.csv','w') as file2:
reader = csv.reader(file1)
# Write column headers without quotes
headers = reader.next()
str1 = ''.join(headers)
writer = csv.writer(file2)
writer.writerow(headers)
# Write all other rows with quotes
writer = csv.writer(file2, quoting=csv.QUOTE_ALL)
for row in reader:
writer.writerow(row)
此脚本成功完成了 ALL 列中的上述两项任务。
例如这个原始的.csv:
Column 1, Column 2, Column 3, Column 4
Fred, Flintstone, 5'10", black hair
Wilma, Flintstone, five feet seven inches, red hair
Barney, Rubble, 5 feet 2" inches, blond hair
Betty, Rubble, 5 foot 7, black hair
变成这样:
Column 1, Column 2, Column 3, Column 4
"Fred"," Flintstone"," 5'10"""," black hair"
"Wilma"," Flintstone"," five feet seven inches"," red hair"
"Barney"," Rubble"," 5 feet 2"" inches"," blond hair"
"Betty"," Rubble"," 5 foot 7"," black hair"
但是,如果我只想在 第 3 列(实际上偶尔有双引号的那一列)中完成此操作,该怎么办?
换句话说,我怎么能得到这个……?
Column 1, Column 2, Column 3, Column 4
Fred, Flintstone," 5'10""", black hair
Wilma, Flintstone," five feet seven inches", red hair
Barney, Rubble," 5 feet 2"" inches", blond hair
Betty, Rubble," 5 foot 7", black hair
【问题讨论】:
标签: python python-2.7 csv