Python Forum
Iterate 2 large text files across lines and replace lines in second file - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Iterate 2 large text files across lines and replace lines in second file (/thread-28926.html)

Pages: 1 2


RE: Iterate 2 large text files across lines and replace lines in second file - bowlofred - Aug-10-2020

Same as the sample code above. Instead of setting line1, line2 directly from the filehandle, set them from a readline().

line1 = fileA.readline()
line2 = fileB.readline()
while all(line1, line2):
    # do loop stuff here
    # at end of loop, read the lines again
    line1 = fileA.readline()
    line2 = fileB.readline()



RE: Iterate 2 large text files across lines and replace lines in second file - medatib531 - Aug-10-2020

Ok so this is the code I have

with open("file1", 'r') as fileA, open("file2", 'r+') as fileB:
    line1 = fileA.readline()
    line2 = fileB.readline()
    line_start = fileB.tell()
    while all(line1, line2):
        if line1 == line2:
            replace = "00"
            fileB.seek(line_start)
            fileB.write(replace)
        line_start = fileB.tell()
        line1 = fileA.readline()
        line2 = fileB.readline()
and I get error
TypeError: all() takes exactly one argument (2 given)
Also not sure about the right order on tell() and readline()


RE: Iterate 2 large text files across lines and replace lines in second file - bowlofred - Aug-10-2020

Yeah, I typed that up quickly. Probably better would be

with open("file1", 'r') as fileA, open("file2", 'r+') as fileB:
    line_start = fileB.tell() # want the current position before reading the line.
    line1 = fileA.readline()
    line2 = fileB.readline()
    while line1 and line2:
        if line1 == line2:
            replace = "00"
            fileB.seek(line_start)
            fileB.write(replace) # make sure you're writing the correct length here. Too long and you'll merge lines.  Too short and you'll leave old data behind.
        line_start = fileB.tell()
        line1 = fileA.readline()
        line2 = fileB.readline()



RE: Iterate 2 large text files across lines and replace lines in second file - medatib531 - Aug-10-2020

Worked, needed a minor tweak to make it work for the very last line as well

with open("file1", 'r') as fileA, open("file2", 'r+') as fileB:
    line_start = fileB.tell()
    line1 = fileA.readline()
    line2 = fileB.readline()
    while line1 and line2:
        if line1 == line2:
            replace = "00"
            fileB.seek(line_start)
            fileB.write(replace) 
        line_start = fileB.tell()
        if line1 != line2: line1 = fileA.readline()
        line2 = fileB.readline()
Thanks!