Question

I am attempting to open two files then take the first line in the first file, write it to an out file, then take the first line in the second file and append it to the same line in the output file, separated by a tab.

I've attempted to code this, and my outfile just ends up being the whole contents of the first file, followed by the entire contents of the second file. I included print statements just because I wanted to see something going on in the terminal while the script was running, that is why they are there. Any ideas?

import sys


InFileName = sys.argv[1]                 

InFile = open(InFileName, 'r') 

InFileName2 = sys.argv[2]

InFile2 = open(InFileName2, 'r')

OutFileName = "combined_data.txt"

OutFile = open(OutFileName, 'a')

for line in InFile:
    OutFile.write(str(line) + '\t')
    print line
    for line2 in InFile2:
        OutFile.write(str(line2) + '\n')
        print line  

InFile.close()
InFile2.close()
OutFile.close()
Was it helpful?

Solution

You can use zip for this:

with open(file1) as f1,open(file2) as f2,open("combined_data.txt","w") as fout:
     for t in zip(f1,f2):
         fout.write('\t'.join(x.strip() for x in t)+'\n')

In the case where your two files don't have the same number of lines (or if they're REALLY BIG), you could use itertools.izip_longest(f1,f2,fillvalue='')

OTHER TIPS

Perhaps this gives you a few ideas: Adding entries from multiple files in python

o = open('output.txt', 'wb')

fh = open('input.txt', 'rb')
fh2 = open('input2.txt', 'rb')

for line in fh.readlines():
    o.write(line.strip('\r\n') + '\t' + fh2.readline().strip('\r\n') + '\n')

## If you want to write remaining files from input2.txt:
# for line in fh2.readlines():
#     o.write(line.rstrip('\r\n') + '\n')

fh.close()
fh2.close()
o.close()

This will give you:

line1_of_file_1        line1_of_file_2
line2_of_file_1        line2_of_file_2
line3_of_file_1        line3_of_file_2
line4_of_file_1        line4_of_file_2

Where the space in my output example is a [tab] Note: no line ending is appended to the file for obvious reasons.

For this to work, the linendings would need to be proper in both file 1 and 2. To check this:

print 'File 1:'
f = open('input.txt', 'rb')
print [r.read[:200]]
f.close()

print 'File 2:'
f = open('input2.txt', 'rb')
print [r.read[:200]]
f.close()

This should give you something like

File 1:
['This is\ta lot of\t text\r\nWith a few line\r\nendings\r\n']
File 2:
['Give\r\nMe\r\nSome\r\nLove\r\n']

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top