LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Using python to merge two text files line for line (http://www.linuxquestions.org/questions/programming-9/using-python-to-merge-two-text-files-line-for-line-818308/)

simplified 07-06-2010 01:54 PM

Using python to merge two text files line for line
 
Hi

I'm a bit new to Python programming and hoped that someone might be able to help with a problem I'm having. What I essentially want to do is to combine two text files line for line. I know how to do this in a bash script so to give you a better idea here's the code for that:

Code:

paste -d ';' file1 file2 > merged_file1_and_file2
This is basically for adding on values to the end of a CSV file that uses ';' as the delimiter. So say file1 said:

dog
cat
sheep

and file2 said:

bark
meow
baa

then running this command would create merged_file1_and_file2 which would be:

dog;bark
cat;meow
sheep;baa

The code I'm using at the moment is:

Code:

   
csvraw = open("csvfile.txt", "r")
    stamps = open("delimited.txt", "r")
   
    for line in csvraw:
        print(line.rstrip())
        for line in stamps:
            print(line.rstrip())

As I'm sure any experienced python programmer will see, this prints out the first line of the file "csvraw" and then all of the lines of "stamps" and then the remainder of "csvraw".

What I'd like to do is something like: (pseudo code, I know it's not python ;-))

Code:

for each line in csvraw and stamps:
    print both lines on the same line

Is this possible? I've tried googling and my Python Pocket Reference hasn't been much help. I've looked at pickling but that doesn't seem appropriate.

TIA, Simplified.

simplified 07-06-2010 02:09 PM

Sorted!
 
Just had an epiphany...

Code:

    csvraw = open("csvfile.txt", "r")
    stamps = open("delimited.txt", "r")
   
    for line in csvraw:
        print(line.rstrip() + stamps.readline().strip())

I hope this helps you out if you're stuck!


All times are GMT -5. The time now is 08:15 AM.