简体   繁体   English

csv.writer 将每一行写入单独的单元格/列

[英]csv.writer writing each line into separate cell/column

Objective : to extract each paragraph from from a large text file and store it in.csv file. Objective :从大文本文件中提取每个段落并将其存储在.csv 文件中。 new line("\n") is acting as a delimiter. new line("\n") 充当分隔符。

this is code im using:这是我使用的代码:

import csv
input_file = open('path', 'r')
output_file = open('path', 'a+')
writer = csv.writer(output_file)
list = []
for line in input_file:
    if line != "\n":
        list.append(line)
    else:
        writer.writerow(list)
        list.clear()

the goal here is to parse & append each line into a list until we encounter a "\n" and store the content present in the list into a single cell in the.csv file.这里的目标是将 & append 每一行解析成一个列表,直到我们遇到"\n"并将列表中存在的内容存储到.csv文件的single cell中。

code is working fine, but due to some reason, each line is been printed in separate column/cell instead of printing the entire paragraph into a single cell.代码工作正常,但由于某种原因,每一line打印在单独的列/单元格中,而不是将整个paragraph打印到单个单元格中。

expected output:预期 output:
row 1: this is stackoverflow row 1:这是 stackoverflow
python language is used.使用 python 语言。

current output: row 1: this is stackoverflow |当前 output: row 1:这是 stackoverflow | python language is used.使用 python 语言。

what am I missing here?我在这里想念什么?

writerow method writes the contents in a single row, ie each element in a separate column in the same row. writerow方法将内容写入单行,即在同一行的单独列中的每个元素。

Wouldn't this do the trick for you?这不是对你有用吗?

import csv

with open(input_path, 'r') as f:
    paragraphs = f.read().split('\n\n')

with open(output_path, 'w') as f:
    writer = csv.writer(f)
    writer.writerows(enumerate(paragraphs))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM