[英]Replacing text from one file from another file
f1.write(line2)可以工作,但它不会替换文件中的文本,而只是将其添加到文件中。 我希望file1与file2相同(如果它们不同),方法是用file2中的文本覆盖file1中的文本
这是我的代码:
with open("file1.txt", "r+") as f1, open("file2.txt", "r") as f2:
for line1 in f1:
for line2 in f2:
if line1 == line2:
print("same")
else:
print("different")
f1.write(line2)
break
f1.close()
f2.close()
我希望file1与file2相同
import shutil
with open('file2', 'rb') as f2, open('file1', 'wb') as f1:
shutil.copyfileobj(f2, f1)
由于您不必读取file1,因此速度会更快。
您的代码无法正常工作,因为您必须将文件的当前指针(使用f1.seek()
放置在正确的位置才能编写该行)。
在您的代码中,您首先读取一行,然后将指针放置在刚读取的行之后。 写入时,该行数据将被写入该位置的文件中,从而复制该行。
由于行的大小可以不同,因此进行这项工作并不容易,因为即使正确放置了指针,如果对某行进行了修改以使其变大,则在写入时会覆盖文件中下一行的一部分。 无论如何,您最终将不得不至少将一部分文件内容缓存在内存中。
最好截断文件(擦除其内容)并直接写入其他文件数据-这样它们将是相同的。 这就是答案中的代码。
我将read
两个文件,创建一个替换了不同元素的新list
,然后将整个列表写入该文件
with open('file2.txt', 'r') as f:
content = [line.strip() for line in f]
with open('file1.txt', 'r') as j:
content_a = [line.strip() for line in j]
for idx, item in enumerate(content_a):
if content_a[idx] == content[idx]:
print('same')
pass
else:
print('different')
content_a[idx] = content[idx]
with open('file1.txt', 'w') as k:
k.write('\n'.join(content_a))
file1.txt
之前:
chrx@chrx:~/python/stackoverflow/9.28$ cat file1.txt this that this that who #replacing that what blah
code
输出:
same same same same different same same same
file1.txt
之后:
chrx@chrx:~/python/stackoverflow/9.28$ cat file1.txt this that this that vash #replaced who that what blah
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.