'How to read a file from one line to the end and write another from that same line to the end?

print("Type: \n 1 - To read and translate from the beginning of the file\n 2 - To read from a specific line of the file")
how_to_read = str(input())

if (how_to_read == "1"):
    read_mode = "w"
    total_previous_lines = 0 #Read the file from the beginning
elif(how_to_read == "2"):
    read_mode = "a"
    with open('translated_file.xml') as last_translated_file:
        total_previous_lines = sum(1 for line in last_translated_file) - 1  #Number of lines, to which one is subtracted for the last line that is empty and must be replaced from it if it is the case
        print(total_previous_lines)
else:
    print("You have not chosen any of the valid options")
    read_mode = None

if(read_mode):
    with open("en-sentiment.xml", "r") as read_file:
        #I NEED TO READ "en-sentiment.xml" FROM total_previous_lines + 1 (that is, the next to the last one that already existed, to continue...)

        with open("translated_file.xml", read_mode) as write_file:
            # I NEED TO WRITE "translated_file.xml" FROM total_previous_lines + 1 (ie the next to the last one, to continue...)

            #For each line of the file that it reads, we will write the file with the write function.
            for line in read_file:
                print(repr(line))

That's my code, and I was having trouble reading the .xml files from that total_previous_lines, since the statement with open() as ..._file: naturally reads from the beginning iterating line by line, but in this case if the file already existed, if with the opening mode a you wanted to write from total_previous_lines you would have the problem that it starts to iterate from the beginning.

And with the opening mode "r" the same thing would happen if you want to read from total_previous_lines with a value other than 0 (that is, the first line)



Solution 1:[1]

Read about seek() in python. But better use an xml parser like ElementTree.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 nOs