【问题标题】:Terminate line for only one column of each row while writing csv在写入csv时仅终止每行的一列
【发布时间】:2020-06-29 10:19:19
【问题描述】:

我的列表列表如下:

list = [["1","this is first note.[CR][LF] This is next line","type1"], ["2","this is second note[CR][LF]. This is next line","type2"]]

我尝试将 csv 写为:

writer = open('test.csv', 'w')
csv_writer = csv.writer(writer, delimiter=";", quoting=csv.QUOTE_ALL, )
for row in rows:
        if len(row) > 0:
            row[1] = str(row[1]).replace("[CR]", "\r").replace("[LF]", "\n")
            logging.info("writing rows into csv " + str(count))
            csv_writer.writerow(row)
writer.close()

我期望得到以下结果:

|-----------|---------------------------|-------|
|   id      |     note                  |type   |
|-----------|---------------------------|-------|
|    1      |    this is the first note.|       |
|           |      this is next line    |type1  |
|           |                           |       |
|-----------|---------------------------|-------|

但我得到了以下结果:

|--------------------|---------------------------|-------|
|   id               |     note                  |type   |
|--------------------|---------------------------|-------|
|    1               |    this is the first note.|       |
|this is next line   |          type1            |       |
|                    |                           |       |
|--------------------|---------------------------|-------|

是否可以在第一个表中按预期写入 csv?由于我是 python 和 csv 的新手,请有人帮忙吗?

【问题讨论】:

    标签: python-3.x csv export-to-csv


    【解决方案1】:

    鉴于您的数据,例如:

    listt = [["1","this is first note.[CR][LF] This is next line","type1"], ["2","this is second note[CR][LF]. This is next line","type2"]]

    我们可以使用pandas库方便地写入csv:

    import pandas as pd
    
    df = pd.DataFrame(listt, columns=["id", "note", "type"]) #Instantiate a dataframe
    
    df["note"] = df.note.str.replace("\[CR\]", "\r").str.replace("\[LF\]", "\n") #Replace the strings you want
    
    df.to_csv("yourfilename.csv")
    

    您必须检查换行符是否被您的 CSV 读取程序正确解析,但换行符现在应该在那里。

    【讨论】:

      猜你喜欢
      • 2018-02-17
      • 2019-06-10
      • 2017-11-20
      • 2021-06-07
      • 1970-01-01
      • 2016-04-02
      • 2016-12-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多