There are many interesting answers as to how to do that, but none of them show how to fix your code. I find it better for learning when we understand our own mistakes, rather than get a solution ;)
Tuple in the same line has object names the other way around - you want line (from 1st file) stripped and item (from 2nd) split and took second element (that would be [1]
)
With those small changes (and others, described in comments), we get:
with open('1','r') as first:
with open('2', 'r') as second:
#data1 = first.readlines() #don't do that, iterate over the file
for line in first: #changed
output = [(line.strip(), item.split(' ')[1]) for item in second]
f = open("1+2","a") #use mode "a" for appending - otherwise you're overwriting your data!
f.write("{} {}".format(output)) # don't mix python2 and python3 syntax, removed extra newline
f.close()
But it's still wrong. Why? Because for item in second
- you're parsing whole second file here. In the first ever line from 1st file.
We need to change it so that we only take one element. I'd recommend you read this question and explanations about iterators.
Now let's apply this knowledge: second
is an iterator. We only need one element from it and we need to do it manually (because we're in another loop - looping over 2 things at once is a tricky thing), so we'll be using next(second)
:
with open('1','r') as first:
with open('2', 'r') as second:
for line in first:
item = next(second)
output = (line.strip(), item.split(' ')[1]) #no list comprehension here
f = open("1+2","a")
f.write("{} {}".format(*output)) #you have to unpack the tuple
f.close()
Explanation about unpacking - basically, when you pass just output
, Python sees it as once element and doesn't know what to do with the other {}
. You have to say "hey, treat this iterable (in this case: 2-element tuple) as single elements, not a whole" and that's how this *
does. :)