csv.writer 将每一行写成单独的 cell/column
csv.writer writing each line into separate cell/column
Objective
:从大型文本文件中提取每个段落并将其存储在 .csv 文件中。换行符("\n") 用作分隔符。
这是我使用的代码:
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()
这里的目标是解析每一行并将其附加到列表中,直到我们遇到 "\n"
并将列表中存在的内容存储到 .csv 文件中的 single cell
中。
代码工作正常,但由于某种原因,每个 line
都打印在单独的 column/cell 中,而不是将整个 paragraph
打印到一个单元格中。
预期输出:
row 1:
这是 Whosebug
python 使用语言。
当前输出:
row 1:
这是 Whosebug | python 使用的语言。
我在这里错过了什么?
writerow
方法将内容写入单行,即每个元素在同一行的单独列中。
这对你有用吗?
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))
Objective
:从大型文本文件中提取每个段落并将其存储在 .csv 文件中。换行符("\n") 用作分隔符。
这是我使用的代码:
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()
这里的目标是解析每一行并将其附加到列表中,直到我们遇到 "\n"
并将列表中存在的内容存储到 .csv 文件中的 single cell
中。
代码工作正常,但由于某种原因,每个 line
都打印在单独的 column/cell 中,而不是将整个 paragraph
打印到一个单元格中。
预期输出:
row 1:
这是 Whosebug
python 使用语言。
当前输出:
row 1:
这是 Whosebug | python 使用的语言。
我在这里错过了什么?
writerow
方法将内容写入单行,即每个元素在同一行的单独列中。
这对你有用吗?
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))