[英]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将b每一行的内容添加到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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.