[Tutor] Newbie append puzzle

Michael Janssen Janssen at rz.uni-frankfurt.de
Sun Nov 2 10:27:50 EST 2003


On Sun, 2 Nov 2003, Tim Ronning wrote:

> BTW. My Opera mail reader/writer is messing up indentation somehow.

[you got probably a tab-problem. code below mixes tabs and spaces]

> Let's try this.
>
> elif choice == '3':
>
> 	def append(mp3):
>            		app = open("playlist","a")
>            		app.write(mp3)
>           		app.close()
>         	newmp3 = raw_input("New mp3: ")
> 	append(newmp3)
>
> elif choice == '4':
>
> 	def makeaList(s):
> 			anothermp3 = string.split(s)
> 			return anothermp3
>
> 	playlist = open("playlist","r")
>         	mp3list = []
> 	for line in playlist.readlines():
> 			mp3list = mp3list + makeaList(line)
>
> 	playlist.close()
>         	delnr = int(raw_input("Which number? "))
> 	del mp3list[delnr]
> 	listlen = len(mp3list)
>
>         	def append(mp3):
> 			app = open("playlist.new","a")
> 			app.write(mp3)
> 			app.close()
>         	n = 0
> 	while n < listlen:
> 			append(mp3list[n])
> 			n = n + 1
>
> The problem: The append() function under choice "3" appends the raw_input
> on a new line in the playlist file. Simple ascii. This is correct. The
> append() function under choice "4" appends all the list items on one single
> line without spaces,

certainly choice "4" "mp3" strings manage somehow to get rid of their
newlines. The newline was originally delivered by "raw_input". Hint:
string.split splits per default by any kind of whitespace....

Best (instead of making shure that your code never tries to "append" a
string, that doesn't end in newline) is to rewrite your "append"
function, so that it test itself if the "mp3" string ends with a
newline. I assume, you want to write that bit yourself (Feel free to
ask on tutor if you can't get it right - or post your solution)?

Note: now where you need to enhance your "append" function it becomes
even more sensible to define it only once: Just define it before any
if-clause and you won't have to do every bugfix twice.

Hey, welcome at tutor and python :-)


Michael

> this is not what I want. I want them on separate
> lines. I have a feeling the answer is embarasing simple and probably
> steering me right in the face, but somehow I don't see it. Anyone?
>  Best regards
>  Tim Ronning
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



More information about the Tutor mailing list