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))
那是我的代碼,我無法從中讀取 .xml 檔案total_previous_lines,因為該陳述句with open() as ..._file:自然地從開頭逐行迭代讀取,但在這種情況下,如果檔案已經存在,如果使用打開模式 a 你想寫從total_previous_lines你那里會有一個問題,它從一開始就開始迭代。
"r"如果您想total_previous_lines使用 0 以外的值(即第一行)讀取,在打開模式下也會發生同樣的事情
uj5u.com熱心網友回復:
忽略您問題中的代碼...
假設您通過某種方式在輸入檔案中找到了要開始讀取的行,并且您想將該輸入檔案的其余部分復制到其他檔案中。
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)
uj5u.com熱心網友回復:
閱讀 Python 中的 seek()。但最好使用像 ElementTree 這樣的 xml 決議器。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/430401.html
標籤:Python python-3.x 文件 读取文件 写文件
