使CSV转义双引号

时间:2018-09-20 22:03:47

标签: python python-2.7 csv arcmap

我需要准备一个.csv文件,以便处理该文件的程序(ArcMap)忽略双引号。 Arc正在将该行上所有后续单元格的内容混合到任何包含双引号的先前单元格中。例如:

enter image description here

...而且根本不会再处理其他行。

如何使CSV转义双引号以在ArcMap(10.2)中成功处理?

3 个答案:

答案 0 :(得分:1)

假设df是为csv文件创建的DataFrame,如下所示

df = pd.read_csv('filename.csv')

让我们假设comments是发生问题的列的名称,即您要用空字符串()替换每个双引号(“)。

以下一线为您做到这一点。它将用空字符串替换df['comments']中每一行的所有双引号。

df['comments'] = df['comments'].apply(lambda x: x.replace('"', ''))

lambda捕获变量df['comments']x中的每一行。

编辑:要转义双引号,您需要将字符串转换为原始格式。再一次,与上面的非常相似。

df['comments'] = df['comments'].apply(lambda x: r'{0}'.format(x))

字符串前的r是转义符,用于转义python中的字符。

答案 1 :(得分:0)

您可以尝试使用csv模块读取文件并将其写回,以期其他工具可以更容易地理解输出格式。请参阅formatting options的文档。

import csv
with open('in.csv', 'r') as fin, open('out.csv', 'w') as fout:
    reader = csv.reader(fin, delimiter='\t')
    writer = csv.writer(fout, delimiter='\t')
    # alternative:
    # writer = csv.writer(fout, delimiter='\t', escapechar='\\', doublequote=False)
    for line in reader:
        writer.writerow(line)

答案 2 :(得分:0)

对我有用的是编写一个模块,对CSV文件进行一些“预处理”,如下所示。关键行是“编写器”具有参数“ quoting = csv.QUOTE_ALL”的位置。希望这对其他人有用。

def work(Source_CSV):
    from __main__ import *
    import csv, arcpy, os

    # Derive name and location for newly-formatted .csv file
    Head = os.path.split(Source_CSV)[0]
    Tail = os.path.split(Source_CSV)[1]
    name = Tail[:-4]
    new_folder = "formatted"
    new_path = os.path.join(Head,new_folder)
    Formatted_CSV = os.path.join(new_path,name+"_formatted.csv")
    #arcpy.AddMessage("Formatted_CSV = "+Formatted_CSV)

    # Populate the new .csv file with quotation marks around all field contents ("quoting=csv.QUOTE_ALL")
    with open(Source_CSV, 'rb') as file1, open(Formatted_CSV,'wb') as file2:

        # Instantiate the .csv reader
        reader = csv.reader(file1, skipinitialspace=True)   

        # Write column headers without quotes
        headers = reader.next()  # 'next' function actually begins at the first row of the .csv.  
        str1 = ''.join(headers)
        writer = csv.writer(file2)
        writer.writerow(headers)

        # Write all other rows wrapped in double quotes
        writer = csv.writer(file2, delimiter=',', quoting=csv.QUOTE_ALL)

        # Write all other rows, at first quoting none...
        #writer = csv.writer(file2, quoting=csv.QUOTE_NONE,quotechar='\x01')

        for row in reader:
            # ...then manually doubling double quotes and wrapping 3rd column in double quotes.
            #row[2] = '"' + row[2].replace('"','""') + '"'
            writer.writerow(row) 

        return Formatted_CSV