I'm new to python. What I'm trying to do is combing file 'a' and file 'b' into one file LINE by LINE.
For example,
text file a = a ("\n") b("\n") c
text file b = 1("\n")2("\n") 3
text file new will contain a 1("\n") b 2("\n") c 3
def main():
f1 = open("aaa.txt")
f2 = f1.readlines()
g1 = open("bbb.txt")
g2 = g1.readlines()
h1 = f2+g2
print(h1)
I'm so sorry this is my first time using stackoverflow ..
Points :
with. No need to close file.zip function to combine two list. Code without zip with comments inline:
combine =[]
with open("x.txt") as xh:
with open('y.txt') as yh:
with open("z.txt","w") as zh:
#Read first file
xlines = xh.readlines()
#Read second file
ylines = yh.readlines()
#Combine content of both lists
#combine = list(zip(ylines,xlines))
#Write to third file
for i in range(len(xlines)):
line = ylines[i].strip() + ' ' + xlines[i]
zh.write(line)
Content of x.txt:
1
2
3
Content of y.txt:
a
b
c
Content of z.txt:
a 1
b 2
c 3
Code with zip function:
with open("x.txt") as xh:
with open('y.txt') as yh:
with open("z.txt","w") as zh:
#Read first file
xlines = xh.readlines()
#Read second file
ylines = yh.readlines()
#Combine content of both lists and Write to third file
for line1, line2 in zip(ylines, xlines):
zh.write("{} {}\n".format(line1.rstrip(), line2.rstrip()))
Read more about file handling and using the in-built functions efficiently.
For your query just using h1 = f2+g2 is not the way.
a=open('a.txt','r').readlines()
b=open('b.txt','r').readlines()
with open('z.txt','w') as out:
for i in range(0,10): #this is for just denoting the lines to join.
print>>out,a[i].rstrip(),b[i]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With