Python Forum
append a string to a modified line
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
append a string to a modified line
#1
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
Reply
#2
Can you post some real lines of your corrupted m3u?
Reply
#3
(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
Reply
#4
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
Mr_Blue likes this post
Reply
#5
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.
Reply
#6
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')
Mr_Blue likes this post
Reply
#7
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)
Mr_Blue likes this post
Reply
#8
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?
Reply
#9
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/
Reply
#10
(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
Mr_Blue likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to capture string from a line to certain line jerald 1 427 Jun-30-2021, 05:13 PM
Last Post: Larz60+
  How to create new line '/n' at each delimiter in a string? MikeAW2010 3 807 Dec-15-2020, 05:21 PM
Last Post: snippsat
  How to rename a CSV file by adding MODIFIED in the filename? Python_User 25 2,568 Dec-13-2020, 12:35 PM
Last Post: Larz60+
  How to print string multiple times on new line ace19887 7 1,916 Sep-30-2020, 02:53 PM
Last Post: buran
  Add new line after finding last string in a region Nigel11 1 682 Aug-08-2020, 10:00 PM
Last Post: Larz60+
  Searching string in file and save next line dani8586 2 777 Jul-10-2020, 09:03 AM
Last Post: dani8586
  Finding line numbers starting with certain string Sutsro 3 1,017 Jun-27-2020, 12:36 PM
Last Post: Yoriz
  Cant Append a word in a line to a list err "str obj has no attribute append Sutsro 2 932 Apr-22-2020, 01:01 PM
Last Post: deanhystad
  Python convert multi line into single line formatted string karthidec 2 3,958 Dec-23-2019, 12:46 PM
Last Post: karthidec
  how to convert list to string after append !! evilcode1 3 1,189 Dec-16-2019, 09:50 AM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020