【问题标题】:How to row wise append two .csv files without using pandas如何在不使用熊猫的情况下逐行追加两个 .csv 文件
【发布时间】:2021-04-27 04:03:05
【问题描述】:
我想附加两个具有相同列数/名称的 .csv 文件并保存输出文件。但是我不想使用 pandas concat 或 pandas read_csv。有没有办法使用纯 python 'with open' 来实现这一点?
【问题讨论】:
-
查看类似的question。他们只是试图附加数据,但您可以在循环中打开第二个文件并将其附加到第一个文件。
标签:
python
csv
with-statement
【解决方案1】:
这样的事情应该可以工作:
# read first file
with open('file1.csv', 'r') as txt:
lines = txt.readlines()
# extend the list with the lines from the second file
with open('file2.csv', 'r') as txt:
lines.extend(txt.readlines())
# remove \n from the end of each line
lines = [line.strip() for line in lines]