(Sep-15-2021, 05:06 PM)Mr_Blue Wrote: i think it could be good practice to close a fileThe point of using
with open("new_playlist.m3u", "w") as f: f.write(out_text) f.close() # Not needed
with open
is that it close the file automatically.Quote:would you care to explain the code?Learn to take out pieces and test it interactively on of the strength of Python,
then easier to see what going on,an loop is just doing this serval times 🧬
>>> out_text = "" >>> out_text += 'Hello' >>> out_text += 'World' >>> out_text 'HelloWorld'
>>> out_text = "" >>> line = '#EXTINF:137,Choir - When Johnny Comes Marching Home' name = line.split(",", 1)[1] >>> name 'Choir - When Johnny Comes Marching Home' >>> out_text += f'\n{name}.mp3\n' >>> out_text '\nChoir - When Johnny Comes Marching Home.mp3\n'Or a other option as in my code that don't collect in
out_text
,just write it directly to the file.with open('songs.txt') as f,open('songs_out.txt', 'w') as f_out: for line in f: line = line.strip() if line.startswith("#EXTINF"): f_out.write(f'{line}\n') name = line.split(",")[1] f_out.write(f'{name}.mp3\n')
Output:#EXTINF:137,Choir - When Johnny Comes Marching Home
Choir - When Johnny Comes Marching Home.mp3
#EXTINF:191,Glenn Miller - When Johnny Comes Marching Home
Glenn Miller - When Johnny Comes Marching Home.mp3
#EXTINF:308,Chad Mitchell Trio - Johnnie
Chad Mitchell Trio - Johnnie.mp3
#EXTINF:205,Joan Baez - Johnny, I Hardly Knew Yeh
Joan Baez - Johnny.mp3
#EXTINF:213,Clancy Brothers & Tommy Makem - Johnny I Hardly Knew You
Clancy Brothers & Tommy Makem - Johnny I Hardly Knew You.mp3