Python连接文件

时间:2018-04-13 13:56:25

标签: python file text

文件1.csv:

traider1,domain.net,tomb,Raider1
traider,domain.net,tomb,Raider

file 2.txt:

TECH-1377
TECH-1366

如何将这两个文件合并为第三个?

所以我可以得到3.csv:

traider1,domain.net,tomb,Raider1,TECH-1377
traider,domain.net,tomb,Raider,TECH-1366

我试过了:

import fileinput

files= ['1.csv','2.txt']

allfiles = fileinput.input(files)

for line in allfiles: # this will iterate over lines in all the files
    print(line)

得到了

traider1,domain.net,tomb,Raider1

traider,domain.net,tomb,Raider

TECH-1377

TECH-1366

1 个答案:

答案 0 :(得分:1)

import csv
with open('file 1.csv', 'r') as f:
    data = f.readlines()              #Read file1

with open('file 2.csv', 'r') as f2:
    data2 = f2.readlines()            #Read file2

with open('file 2.csv', 'w') as f3:
    writer = csv.writer(f3, delimiter=',')
    for i, line in enumerate(data):
        val = "{0},{1}".format(line.strip(), data2[i].strip())
        writer.writerow(val.split(","))