在python中逐行组合两个csv文件内容

问题描述 投票:1回答:1

我正在使用python中的两个csv文件。我必须以这样的方式组合这两个csv文件的内容,以便合并文件的两列。

file1.csv

john,willy,wight
clark,ricky,martin
shane,gilly,rocky

file2.csv

1
2
3

我的输出文件如下所示:

output.csv

john,willy,wight,1
clark,ricky,martin,2
shane,gilly,rocky,3

最初我尝试了一些我在下面写的代码:

myfile1 = open("file1.csv","r")
myfile2 = open("file2.csv","r")
myfile3 = open("file3.csv","w")

`for i in myfile1:
    for j in myfile2:
        myfile3.write(i + j)
myfile3.close()
myfile2.close()
myfile1.close()

我得到的输出是:

a,b,c
1
a,b,c
2
a,b,c
3
a,b,c
4
a,b,c
5
a,b,c
6
a,b,c
7

这就是我所尝试过的。帮我解决这个问题。提前谢谢。

python-3.x csv multiple-columns file-handling
1个回答
0
投票

将嵌套循环中的行更改为myfile3.write(i.replace("\n", "") + j)

您的代码中的问题是,当您在ij中读取时,它们最后都有换行符。为了解决这个问题,我将i中的换行符替换为"",以便只写入一个换行符。

顺便说一句,以下代码更整洁:

with open("file1.csv", "r") as myfile1 and open("file2.csv", "r") as myfile2 and open("file3.csv", "w"):
    for i in myfile1 and j in myfile2:
        myfile3.write(i.replace("\n", "") + j)
© www.soinside.com 2019 - 2024. All rights reserved.