【问题标题】:How to add a text delimiter correctly in Python如何在 Python 中正确添加文本分隔符
【发布时间】:2019-08-28 18:25:11
【问题描述】:

我想将一些数据从 DB 导出到 CSV 文件。我需要添加一个'|'特定字段的分隔符。在我导出文件的那一刻,我使用类似的东西: - 对于特定字段(在末尾和开头),我添加“|”:

....
if response.value_display.startswith('|'):
                        sheets[response.sheet.session][response.input.id] = response.value_display
                    else:
                        sheets[response.sheet.session][response.input.id] = '|'+response.value_display+'|'
....
  • 我有这样的 CSV 写入器功能设置:
self.writer = csv.writer(self.queue, dialect=dialect,
                                 lineterminator='\n',
                                 quotechar='',
                                 quoting=csv.QUOTE_NONE,
                                 escapechar=' ',
                                 ** kwargs)

现在它可以工作了,但是当我有 DateTime 字段(空间在哪里)时,作者会添加一些额外的空间。

当我在末尾有默认设置(有时)时,开始 CSV 编写器添加双引号,但我不知道为什么以及它取决于什么。

【问题讨论】:

    标签: python django csv export


    【解决方案1】:

    要删除多余的空格,我会做类似的事情。

        file = open(the_file.csv, w+) #open your csv file
        file.write(file.readline().replace("  ", " ") #finds any two spaces and replaces with one
        file.close()
    

    使用定界符是针对具体情况的。如果你想在开头或结尾添加它。

        delimiter = "|"
        my_str = my_str + delimiter
    

        delimiter = "|"
        my_str = delimiter + my_str
    

    如果您想在其他地方添加分隔符,您可能需要根据上下文获得创意。

    我不确定双引号。我会像空格一样替换。

        file = open(the_file.csv, w+) #open your csv file
        file.write(file.readline().replace("\"", "'") 
        file.close()
    

    假设您想用单引号替换双引号。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-14
      • 2015-12-08
      • 2019-08-24
      相关资源
      最近更新 更多