简体   繁体   中英

How to save a tuple in a Textfile and access it with this code in Python

I really want to finish my personal vocabulary trainer. It works fine, but I am having problems with saving the list into a text file and access it, after exiting the program.

Please note that I am a beginner in Python, so it would be great, if I could have an explanation for the solution. Thanks

Here´s my code so far:

import random
import os

class Entry:
    def __init__(self, deutsch, englisch):
        self.deutsch = deutsch
        self.englisch = englisch

    def toString(self):
        return self.deutsch + " - " + self.englisch

eintraege = [Entry("hallo", "hello")]   **<--Wanna save this list**
directory = r'C:\Users\Peter\desktop'

def eingabe():   #means 'input' in english
    while True:
        deutsch = input("Deutsches Wort: ")
        if deutsch == '#exit#':
            return
        englisch = input("Englisches Wort: ")
        if englisch == '#exit#':
            return
        eintraege.append(Entry(deutsch, englisch))
        w = open('dictionary.txt', 'a')
        w.write(' - '.join(eintraege))  **<---------Problem here; tried multiple solutions**

def abfrage():  #means 'query' in english
    while True:
        i = random.randint(0, len(eintraege) - 1)
        englisch = input("Englische Übersetzung von " + eintraege[i].deutsch + ": ")
        if englisch == '#exit#':
            return
        if eintraege[i].englisch == englisch:
            print("Korrekt!")
        else:
            print("Leider falsch. Richtig wäre:", eintraege[i].englisch)

def printall():
    for eintrag in eintraege:
        print(eintrag.toString)

os.chdir(directory)        
r = open('dictionary.txt', 'r')
r.read()

while True:
    print("Befehle:\n\
1.) eingabe: Ermöglicht die Bearbeitung des Wörterbuchs\n\
2.) abfrage: Zufällige Abfrage der Vokabel\n\
3.) ausgabe: Zeigt alle eingegebenen Vokabel an\n\
4.) beenden: Beendet das Programm\n\n")

    befehl = input("Befehl: ")
    if befehl == 'eingabe':
        eingabe()
    elif befehl == 'abfrage':
        abfrage()
    elif befehl == 'beenden':
        break
    elif befehl == 'ausgabe':  #means 'output' in english
        printall()
    else:
        print("Kein bekannter Befehl!")

I am grateful for any help.

Try to implement _ str _ method in your Entry class:

def __str__(self):
    return '%s - %s' % (self.deutsch, self.englisch)

and then use it as follows:

w.write('\n'.join(eintraege))

You are outputting the wrong data. Instead of

eintraege.append(Entry(deutsch, englisch))

you want:

eintraege.append( Entry(deutsch, englisch).toString() )

or just:

eintraege.append( deutsch + '-' + englisch )

Python does not recognize the "Entry" type and will not automatically convert it to a string, so you need to fill you list with strings, NOT Entry objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM