Home > Software engineering >  Remove multiple lines in text file
Remove multiple lines in text file

Time:09-01

I want to remove the currently being read line and the line before from the text file, but also continue reading until the end of the file.

I have a text file where German words and English words are written every 2 lines. The method I'm currently using saves the content of the two lines saved as two variables, but it exits after the first iteration. I would like for it to go through all the German words.

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) 

Here's a part of the text file

der Außenhandel
    foreign trade
die Mobilität
    mobility
Sozialleistungen
    welfare benefits
der Schichtdienst
    shift work
die Flexibilität
    flexibility

For example, if I guess correctly the word "der Außenhandel" and guess the rest all wrong, I want only the 2 lines (der Außenhandel-foreign trade) be deleted.

It will be updated like this

die Mobilität
    mobility
Sozialleistungen
    welfare benefits
der Schichtdienst
    shift work
die Flexibilität
    flexibility

The rest of the words I will recycle for my 2nd guessing attempt (inspired by Quizlet).

Can someone explain the problem, and how to fix it?

CodePudding user response:

The program is reading the file correctly to start; however, when a correct answer is entered, the program is then writing new records out to the file and positioning the file cursor to the end of the file.

        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

Starting out, as long as an incorrect answer is entered, the program will continue to read lines. But once a correct entry is made, the file "writes", and no more English words are found. Following is some sample output on my terminal displaying that behavior.

@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$

If you deactivate those file "writes" or write the data out to another file, the tests should continue. Give that a try.

Additional Notes:

After reading your comment and seeing you follow-up clarification, you could read in the total file to a text string, then split up the lines placing the data into English and Deutsch strings to prompt for the answer. Please review the following code snippet with those requirements in mind.

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

That way, you can reuse the same file, only rewriting those word pairs that were incorrect. Following is a before and after look at your sample data.

der Außenhandel
    foreign trade
die Mobilität
    mobility
Sozialleistungen
    welfare benefits
der Schichtdienst
    shift work
die Flexibilität
    flexibility

Here is the result of running the program, properly answering the first word and missing the answers for the other words.

@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

Finally, following is the resulting data in the word file.

die Mobilität
mobility
Sozialleistungen
welfare benefits
der Schichtdienst
shift work
die Flexibilität
flexibility

Give that a try and see if that more closely fulfills the spirit of the project.

  • Related