[英]how to append the content of one file at the of the content of another file in python
我想在另一个文件的内容末尾添加一个文件的内容。 我已经说:
The content of the file1 is : james@29@458462
The content of the file2 is : marc@45@4695588
将file2附加到file1之后,我想要拥有:
james@29@458462
marc@45@4695588
这是我尝试使用的代码,但是它用源文件替换了目标文件的内容:
file1=open("test1.txt","a")
file2=open("test2.txt","r")
file1.write(file2.read())
我可以在不替换目标文件内容的情况下,在一个文件末尾附加一个方法吗?
谢谢
在处理文件时尝试使用with( https://docs.python.org/2/reference/compound_stmts.html#the-with-statement ):
with open("test1.txt","a") as file1, open("test2.txt","r") as file2:
for line in file2:
file1.write('\n' + line)
您可以在python中使用bash
脚本命令将两个文件附加在一起,如下所示:
import subprocess as S
CMD="cat file1.txt file2.txt > new.txt"
S.call([CMD],shell=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.