0

I have a list of this form in a .txt file: student1, 2, 3 | student2, 1, 4 I need to call it in a program, add [student3, 3, 5] to the list, and then save it back into the .txt file. I did this but my list looked like this at the end: [[''], ['Student3', '3', '5']]

f = open('classe1.txt','r')
liste = f.read()
liste = liste.split('|')
n = len(liste)
for i in range (n):
    liste[i] = liste[i].split(',')
liste.append(['Student3','3','5'])
liste = str(liste)

f = open('classe1.txt','w')
f.write(liste)

How would you do it ? Thank you !

1 Answers1

0

I'm not entirely sure if I understood your question correctly, but to append a string to a text file, you can use a, i.e.:

with open("classe1.txt", "a") as myfile:
    myfile.write("| student3, 3, 5 ")

If you need to write a python object to a file, you can use json load and dump or Pickle.

Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
  • Actually now that I think about it, it won't work. I really havn't been clear, sorry. In fact I am making a facial recognition device that makes acquaintance for the teachers. The list is a class, and I would like the teacher to have the ability to add or erase a student in the list and directly from the program. Your solution is much simpler to add a student, but I dont see how to erase one with it. – MelvinCERBA May 13 '18 at 13:30
  • You'll probably need to create a database and an interface to manage the records. Your question originally doesn't mention anything about this. You may want to create a new question. – Pedro Lobito May 13 '18 at 13:39
  • Yes I havn't been clear, sorry. I'll see what I can find about databases and python on google, and if I still struggle I'll ask another question. Thanks (and sorry) ! – MelvinCERBA May 13 '18 at 13:45