简体   繁体   中英

Append text file in python

I want to write a code which appends a file as follows:

Input file contents are:

a,b
c,d

I have another file with contents:

2
4

The contents in output file should be:

a,b,2
c,d,4 

I am not able to write a code for this. Can anyone help me out with this please!!

Even if I agree with the first comment, I like internet points.

First, open and read the lines of all files and remove all trailing newline characters

a = [i.strip("\n") for i in open("fileA.txt").readlines()]
b = [i.strip("\n") for i in open("fileb.txt").readlines()]

Add the content from each line of b to a

for i in range(len(a)):
    a[i] = a[i] + "," + b[i]

Finnaly write to a third file

c = open("fileC.txt", "w") # With write permissions
for i in a:
    c.write(i)

Close (and save) all files

a.close()
b.close()
c.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM