使用python将两个文件中的每一行连接为一行

时间:2015-11-23 02:18:11

标签: python string join

我正在尝试使用python将两个文件的行连接起来。任何人都可以帮助我解决这个问题:

文件1:

abc|123|apple

abc|456|orange

abc|123|grape

abc|123|pineapple

abc|123|mango

文件2:

boise

idaho

sydney

tokyo

london

预期输出文件:

abc|123|apple|boise
abc|456|orange|idaho
abc|123|grape|sydney
abc|123|pineapple|tokyo
abc|123|mango|london

**Code tried so far:**

    from itertools import izip
    with open('merged.txt', 'w') as res:
            with open('input1.txt') as f1:
                    with open('input2.txt') as f2:
                            for line1, line2 in zip(f1, f2):
                                    res.write("{} {}\n".format(line1.rstrip(), line2.rstrip()))

我是python的新手,是否有一种简单的方法可以使用分隔符'|'从两个文件追加行。提前谢谢。

2 个答案:

答案 0 :(得分:2)

非常接近,只需将最后一行更改为:

$('#avatar-upload').change(function(e){
 var id = $("input[name=id]").val();
 var file = this.files[0];
 var form = new FormData();
 form.append('avatar-upload', file);
 form.append('uploaded-id', id); //Here is the appended ID
  $.ajax({
    url : 'upload.php',
    type : 'POST',
    cache : false,
    contentType : false,
    processData : false,
    data : form,
    success : function(response) {
         $("#response").css({'display':'block'}).hide().html(response.html).fadeIn(1000);
    }
 });
});

答案 1 :(得分:0)

简洁版本将是这样的

file1=[y.strip() for y in open("file01").readlines()] # read all lines
file2=["|"+x.strip() for x in open("file02").readlines()]  #read all lines but add a "|" at begining of line in file2 
mergedfile=zip(file1,file2) #combine lines
merged_file=open("a_new_file","w")
for line in mergedfile:
    merged_file.write(line[0]+line[1]+"\n") #combine lines
merged_file.close() #close "a_new_file"