我想從文本檔案中洗掉當前正在讀取的行和之前的行,但還要繼續讀取直到檔案末尾。
我有一個文本檔案,其中每 2 行寫一次德語單詞和英語單詞。我當前使用的方法將兩行的內容保存為兩個變數,但在第一次迭代后退出。我想讓它通過所有的德語單詞。
file_name = 'wordlist.txt'
with open(file_name, 'r ') as f:
while True:
deu_word_file = f.readline()
deu_word = deu_word_file.rstrip()
eng_word_file = f.readline()
eng_word = eng_word_file.strip()
if not eng_word:
break
answer = input(eng_word ': ').strip()
if answer == deu_word:
print('Correct!')
f.write(deu_word_file)
f.write(eng_word_file)
else:
print('Wrong - ', deu_word)
這是文本檔案的一部分
der Au?enhandel
foreign trade
die Mobilit?t
mobility
Sozialleistungen
welfare benefits
der Schichtdienst
shift work
die Flexibilit?t
flexibility
例如,如果我猜對了“der Au?enhandel”這個詞,而其余的都猜錯了,我只想洗掉 2 行(der Au?enhandel-foreign trade)。
會這樣更新
die Mobilit?t
mobility
Sozialleistungen
welfare benefits
der Schichtdienst
shift work
die Flexibilit?t
flexibility
其余的單詞我將在我的第二次猜測嘗試中回圈使用(受 Quizlet 啟發)。
有人可以解釋這個問題,以及如何解決它嗎?
uj5u.com熱心網友回復:
程式正在正確讀取檔案以啟動;但是,當輸入正確答案時,程式會將新記錄寫入檔案并將檔案游標定位到檔案末尾。
answer = input(eng_word ': ').strip()
if answer == deu_word:
print('Correct!')
f.write(deu_word_file)
f.write(eng_word_file) # This is moving the file pointer to the end of the file
一開始,只要輸入了錯誤的答案,程式就會繼續讀行。但是一旦輸入正確,檔案就會“寫入”,并且找不到更多的英文單詞。以下是我的終端上顯示該行為的一些示例輸出。
@Una:~/Python_Programs/Deutsch$ python3 Deutsch.py
Oh: Umm
Wrong - Ach
Forbidden: No
Wrong - Verboten
Blue: Bleu
Wrong - Blau
Small: Tiny
Wrong - Klein
Oh: Ach
Correct!
@Una:~/Python_Programs/Deutsch$
如果您停用這些檔案“寫入”或將資料寫入另一個檔案,則測驗應繼續。試試看。
補充說明:
在閱讀了您的評論并看到您的后續說明后,您可以將整個檔案讀入一個文本字串,然后將資料拆分為英語和德語字串以提示答案。請在考慮這些要求的情況下查看以下代碼片段。
file_name = 'wordlist.txt'
with open(file_name, 'r') as f: # Open and read the file
text = f.readlines()
f.close()
with open(file_name, 'w') as f: # Reopen the file in write mode
x = int(len(text) / 2)
for i in range(0, x):
english = str(text[2 * i 1])
deutsch = str(text[2 * i])
answer = input(deutsch.strip() ': ')
if answer == english.strip(): # Don't write correct answer pairs back out to the file
print('Correct!')
else:
print('Wrong - ', english.strip())
f.write(deutsch.strip() '\n') # Write out incorrect answer pairs to the file
f.write(english.strip() '\n')
f.close()
這樣,您可以重復使用相同的檔案,只重寫那些不正確的單詞對。以下是查看您的示例資料的前后對比。
der Au?enhandel
foreign trade
die Mobilit?t
mobility
Sozialleistungen
welfare benefits
der Schichtdienst
shift work
die Flexibilit?t
flexibility
這是運行程式的結果,正確回答了第一個單詞而錯過了其他單詞的答案。
@Una:~/Python_Programs/Deutsch$ python3 Deutsch.py
der Au?enhandel: foreign trade
Correct!
die Mobilit?t: mobil
Wrong - mobility
Sozialleistungen: welfare
Wrong - welfare benefits
der Schichtdienst: flexible
Wrong - shift work
die Flexibilit?t: flex
Wrong - flexibility
最后,以下是word檔案中的結果資料。
die Mobilit?t
mobility
Sozialleistungen
welfare benefits
der Schichtdienst
shift work
die Flexibilit?t
flexibility
試一試,看看這是否更符合專案的精神。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/505055.html
下一篇:如何用C撰寫可移植的二進制檔案?
