0

for example i have this text file: subj.txt and it contains the texts below (subject|time)

astro1|1:00-2:00
act2|2:00-3:00
speech1|4:00-5:00

Btw, i'm using tkinter to create a gui. when a button is clicked, a window with text entry will appear and the program will ask the user to input what course will be deleted. So when a user selects astro1 and the button is clicked, the astro1 will be deleted in the textfile and the ac2 and speech 2 will go up. What is the code for that?

For example I have an entrybox with name self.courseent and i have a function below for the button:

f=open("subj.txt",'r') 
  for x in f:
   a=x.split('|') 
   if self.courseent.get()==a[0]: 
     #the line where the a[0] will be deleted
Hyperboreus
  • 31,997
  • 9
  • 47
  • 87
user3483340
  • 61
  • 1
  • 1
  • 5
  • This [post](http://stackoverflow.com/a/4710090/1982962) can help you. – Kobi K Apr 01 '14 at 06:39
  • yes, this post is near to the solution but in my code, i split the whole line into pipe and it's hard to use the if a[0] != x condition. Using the code above, how can you delete it? – user3483340 Apr 01 '14 at 07:03
  • You can't delete, as the post said and as @Luc DUZAN said you should copy it to a list, remove from the list by tour condition and then write it to the file. – Kobi K Apr 01 '14 at 07:12

1 Answers1

2

You question look a lot like this question :

How to delete a line from a text file in C#?

Actually file doesn't allow you to simply delete a line from a file. What you have to do is to read the all file in memory as an list, delete the line from the list and re-open the file in write mode and rewrite everything. If you file is too big to be loaded in memory, you should write to an other file and then copy your temporary inside your file.

https://docs.python.org/2/library/tempfile.html

Community
  • 1
  • 1
Luc DUZAN
  • 1,299
  • 10
  • 18