[Tutor] Creating a line in a text file every time a button is pressed.
Dave Angel
d at davea.name
Tue Nov 29 19:27:15 CET 2011
On 11/29/2011 10:09 AM, Mic wrote:
> Hey again.
>
> <SNIP most of lengthy code sample>
> root=Tk()
> root.title("testV2")
> app=Mainwindow(root)
> root.mainloop()
>
>
>
What's that code got to do with the question below?
>
> I am now writing another program. It turned out just fine, but I have
> one question.
>
> If button one is pressed I want the program to write, say hi_1, on the
> first line in a text file.
> If button one is pressed again, the first line should be empty.
>
> If button two is pressed I want the program to write hi_2 in the
> second line in the text file.
> If button two is pressed again, the second line in the text file
> should be empty.
>
You can't in general write randomly to a text file, especially if the
line length changes.
> If button three is pressed I want the program to write hi_3 in the
> third line in the text file.
> if button three is pressed again, the third line in the text file
> should be empty.
>
> There shouldn't be any other changes to the program other than this
> above. There is already a text file
> created, the program doesn't need to create one. We can call that file
> "Hi".
>
>
> I hope you understand what I want to do here. I have tried the entire
> evening yesterday to get this to work, I tried using writeline() but I
> can't get it to work.
> What are your suggestions to this?
>
You have at least three choices:
1) abandon the notion of a text file for this purpose. Make it a
structured (binary) file, with fixed length fields.
2) same thing, but fake it in a text file, either by changing the
contents so it's always the same size, or putting in redundant blanks.
3) reconstruct the entire file every time you want to change a line
(other than the last one) to something larger or smaller.
For #3,
If the file is only about 3 lines, keep a list in memory, and dump the
whole list to the file every time you change one of the items.
For #1 and #2, you should look up the seek() method of the file class.
--
DaveA
More information about the Tutor
mailing list