如何在不使用熊猫的情况下按行追加两个 .csv 文件

问题描述

我想附加两个具有相同列数/名称的 .csv 文件并保存输出文件。但是我不想使用pandas concat 或pandas read_csv。有没有办法使用纯 python 'with open' 来实现这一点?

解决方法

这样的事情应该可以工作:

# 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]