简体   繁体   中英

Replacing text from one file from another file

The f1.write(line2) works but it does not replace the text in the file, it just adds it to the file. I want the file1 to be identical to file2 if they are different by overwriting the text from file1 with the text from file2

Here is my code:

 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()

I want the file1 to be identical to file2

import shutil
with open('file2', 'rb') as f2, open('file1', 'wb') as f1:
    shutil.copyfileobj(f2, f1)

This will be faster as you don't have to read file1.

Your code is not working because you'd have to position the file current pointer (with f1.seek() in the correct position to write the line.

In your code, you're reading a line first, and that positions the pointer after the line just read. When writing, the line data will be written in the file in that point, thus duplicating the line.

Since lines can have different sizes, making this work won't be easy, because even if you position the pointer correctly, if some line is modified to get bigger it would overwrite part of the next line inside the file when you write it. You would end up having to cache at least part of the file contents in memory anyway.

Better truncate the file (erase its contents) and write the other file data directly - then they will be identical. That's what the code in the answer does.

I would read both files create a new list with the different elements replaced and then write the entire list to the file

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 before:

 chrx@chrx:~/python/stackoverflow/9.28$ cat file1.txt this that this that who #replacing that what blah 

code output:

 same same same same different same same same 

file1.txt after:

 chrx@chrx:~/python/stackoverflow/9.28$ cat file1.txt this that this that vash #replaced who that what blah 

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