如何从一行读取文件到末尾并从同一行到末尾写入另一个文件?

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

那是我的代码,我无法从 total_previous_lines 读取 .xml 文件,因为语句 with open() as ..._file: 自然地从头开始逐行读取,但是在这种情况下,如果文件已经存在,如果你想使用打开模式 a 从 total_previous_lines 写入,你会遇到从头开始迭代的问题。

如果你想从 total_previous_lines 中读取非 0 的值(即第一行)

,那么在打开模式 "r" 中也会发生同样的事情

阅读 python 中的 seek()。但最好使用像 ElementTree 这样的 xml 解析器。

忽略您问题中的代码...

假设您通过某种方式在输入文件中找到了您想要开始读取的行,并且您想要将该输入文件的其余部分复制到其他文件。

start_line = 20 # for example

with open('input_file.txt') as infile:
    with open('output_file.txt', 'w') as outfile:
        for line in infile.readlines()[start_line:]:
            outfile.write(line)