Python Forum

Full Version: append a string to a modified line
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
i'll try to do this in steps:

1- problem: i must rewrite an corrupted m3u file its lines go:

Output:
#EXTINF123#, Title - Song # let's say for clarity sake that the n line d:\music\title - song.mp3 # this would be the n+1 line
where in fact it should read (caption is important, mind you)

Output:
#EXTINF123#, Title - Song Title - Song.mp3
first part is to erase the line that include d:\music... and then this gives a line that has to be rewritten just below itself, becoming the nth+1 line

the first part is easy i get a file with plenty of lines that have to modified.

Output:
#EXTINF123#, Title - Song #EXTINF123#, Title1 - Song1...
so i shift to the main. question

2- tentative solution

import in_place

    with in_place.InPlace('Soothing.m3u') as file:
        for line in file:
            file.write(line)
            file.write(line[12:])

3- (new) problem:

that will not append the ".mp3" string at the end of the second (n+1) line, ie :

Output:
#ext123#, Title - Song Title - Song
4- (new)tentative solutions

4.1 trying to "add" the string, of course won't do (that would have been too easy ==> no fun)

file.write(line[12:] + ".mp3")
this will add the extension at the beginning of the next line, of course

4.2 "moving" the cursor to the beginning of the n+1 line

with in_place.InPlace('Soothing.m3u') as file:
    for line in file:
        file.write(line)
        file.write(".mp3")
        file.seek(-5,1)
        file.write(line[10:])
this returns an error

Error:
Traceback (most recent call last): File "erase.py", line 7, in <module> file.seek(-5,1) AttributeError: 'InPlace' object has no attribute 'seek'
before, you ask: trying to switch to a .txt file won't change anything to the problem. feel free to test it with a text file, of course.

4.3 join i think i have something here. it doesn't work but if you could help me understand why it would be even more interesting, I suspect... of course i wouldn't turn over the answer :)
import in_place

with in_place.InPlace('Soothing.m3u') as file:
    for line in file:
        file.write(line)
        a = line[12:]
        b = ".mp3"      
        c = a.join(b)
        file.write(c)
it just dispatches b all over the place, giving something like:
Output:
#EXTINF:135,Title - Song .Title - Song mTitle - Song pTitle - Song 3#EXTINF:194,Title1 - Song1
any help's welcome.

OS: ubuntu 18.04

python 2.7 but can use python 3.7
Can you post some real lines of your corrupted m3u?
(Sep-13-2021, 07:51 PM)Axel_Erfurt Wrote: [ -> ]Can you post some real lines of your corrupted m3u?
Output:
#EXTINF:137,Choir - When Johnny Comes Marching Home #EXTINF:191,Glenn Miller - When Johnny Comes Marching Home #EXTINF:308,Chad Mitchell Trio - Johnnie #EXTINF:205,Joan Baez - Johnny, I Hardly Knew Yeh #EXTINF:213,Clancy Brothers & Tommy Makem - Johnny I Hardly Knew You
desired output:
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, I Hardly Knew Ye.mp3 #EXTINF:213,Clancy Brothers & Tommy Makem - Johnny I Hardly Knew You Clancy Brothers & Tommy Makem - Johnny I Hardly Knew You.mp3
This is very different from the first post.

in_text = '''#EXTINF:137,Choir - When Johnny Comes Marching Home
#EXTINF:191,Glenn Miller - When Johnny Comes Marching Home
#EXTINF:308,Chad Mitchell Trio - Johnnie
#EXTINF:205,Joan Baez - Johnny, I Hardly Knew Yeh
#EXTINF:213,Clancy Brothers & Tommy Makem - Johnny I Hardly Knew You
'''

for line in in_text.splitlines():
    if line.startswith("#EXTINF"):
        print(line)
        name = line.split(",")[1]
        print(f'{name}.mp3')
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
it won't do, this won't write a file, just in python.
but an interesting use of
line.split
a shame
file.write ({name}.mp3)
doesn't work.
thank you all the same.
Using Axel_Erfurt code with files it will like this.
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')
change /path/to/playlist.m3u and /path/to/new_playlist.m3u to your needs.

in_text = open("/path/to/playlist.m3u", "r").read()

out_text = ""

for line in in_text.splitlines():
    if line.startswith("#EXTINF"):
        out_text +=  line
        name = line.split(",", 1)[1]
        out_text += f'\n{name}.mp3\n'
    else:
        out_text += f"{line}\n"
        
print(out_text)

with open("/path/to/new_playlist.m3u", "w") as f:
    f.write(out_text)
hello,
thanks to both of you
would you care to explain the code?

    if line.startswith("#EXTINF"): #this makes the loop target a certain line
        out_text +=  line #i see this increments a variable previously set to ""
        name = line.split(",", 1)[1] #i gather this splits line into some sort of array but i fail to grasp its use. 
#could you point me to somewhere this method is explained?
        out_text += f'\n{name}.mp3\n' #at a loss. what's f?
    else:
        out_text += f"{line}\n"
just for the sake of precision, i think it could be good practice to close a file, i guess that print is just to check the whole thing and can be left along, it gives:

in_text = open("playlist.m3u", "r").read()
 
out_text = ""
 
for line in in_text.splitlines():
    if line.startswith("#EXTINF"):
        out_text +=  line
        name = line.split(",", 1)[1]
        out_text += f'\n{name}.mp3\n'
    else:
        out_text += f"{line}\n"
         
with open("new_playlist.m3u", "w") as f:
    f.write(out_text)
f.close()
is it no so?
in_text = open("playlist.m3u", "r").read()

reads the the file into a string

out_text = ""

creates an empty string for later use

for line in in_text.splitlines(): # read every line
    if line.startswith("#EXTINF"):
        out_text +=  line # take over the whole line
        name = line.split(",", 1)[1] # split the line at the first comma and use the text after the comma
        out_text += f'\n{name}.mp3\n' # add newline, name from split and newline to the output
    else:
        out_text += f"{line}\n" # if line has no EXTINF use it without splitting
          
with open("new_playlist.m3u", "w") as f:
    f.write(out_text)
f.close()
f means f-strings in pyhon

https://realpython.com/python-f-strings/
(Sep-15-2021, 05:06 PM)Mr_Blue Wrote: [ -> ]i think it could be good practice to close a file
with open("new_playlist.m3u", "w") as f:
    f.write(out_text)
f.close() # Not needed
The point of using 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
Pages: 1 2