简体   繁体   中英

Replacing a substring in a text file

Gotta write a function that receives a file path and a "new_song" string(aka def my_mp4_playlist(file_path, new_song). The function does 2 things: open the file and write the name of the new song in the 3rd line of the file (in the correct position) and then prints out the new file content.

Starting file content:

Tudo Bom;Static and Ben El Tavori;5:13;
I Gotta Feeling;The Black Eyed Peas;4:05;
Instrumental;Unknown;4:15;
Paradise;Coldplay;4:23;
Where is the love?;The Black Eyed Peas;4:13;

Required print:

Tudo Bom;Static and Ben El Tavori;5:13;
I Gotta Feeling;The Black Eyed Peas;4:05;
**new_song**;Unknown;4:15;
Paradise;Coldplay;4:23;
Where is the love?;The Black Eyed Peas;4:13;

What I have so far:

def my_mp4_playlist(file_path, new_song):
with open(file_path, "r") as reading_file:
    data = reading_file.read()
    data = data.split("\n")
    individual = []
    for element in data:
        individual.append(element.split(";"))

    for song in individual:
        song.remove(song[3]) #this removes a space leftover as the last value in each list

    individual = individual[3][0].replace(individual[3][0], new_song)

    with open(file_path, "w") as writing_file:
        writing_file.write(individual)

    with open(file_path, "r") as complete_file:
        print(complete_file.read())

Unfortunately the replace() method overwrites the entire file content and only new_song appears there. How should I go about this?

This line here is your issue:

individual = individual[3][0].replace(individual[3][0], new_song)

A simple assignment should do the trick:

individual[2][0] = new_song

Please note that I am using index 2 for the 3rd line. Also, you cannot pass a list as parameter to write() , you can only pass a string.

You can use join() and list comprehension to build your string. Your code would then look like this:

def my_mp4_playlist(file_path, new_song):
    with open(file_path, "r") as reading_file:
        data = reading_file.read()
        data = data.split("\n")
        individual = []
        for element in data:
            individual.append(element.split(";"))

        individual[2][0] = new_song

        data = "\n".join([";".join(el) for el in individual])
        with open(file_path, "w") as writing_file:
            writing_file.write(data)

        with open(file_path, "r") as complete_file:
            print(complete_file.read())

Try this one. I did not know if your replacement is always at the same place or has always the same name so I added another attribute where you have to put the name of the part which has to be replaced

path = "YOUR/PATH/FILE.txt"

old_song= "Instrumental"

new_song = "ABCDEFG"

def my_mp4_playlist(file_path, new_song, old_song):
    with open(file_path, "r+") as f:
        content = f.read().replace(old_song, new_song)
        f.truncate(0)
        f.seek(0, 0)
        f.write(content)

my_mp4_playlist(path, new_song, old_song)

I will just tell you the mistake in your code.

individual = individual[3][0].replace(individual[3][0], new_song)
  • You have mentioned it as 3rd element so individual[3][0] should be individual[2][0]

  • This one replaces individual with new value of individual[2][0] .

    But you just need to update that line:

     individual[2][0] = individual[2][0].replace(individual[2][0], new_song)

    which can be further simplified to:

     individual[2][0] = new_song

First of all, as somebody said, you don't need to split the data, you can use reading_file.readlines() .

Secondly, you said you want to replace the third line, not the forth, but in your code you are doing individual = individual[3][0].replace(individual[3][0], new_song)

Remember that lists starts with the index 0.

With that being said, here's what I think would work:

def my_mp4_playlist(file_path, new_song):
    with open(file_path, "r") as reading_file:
            data = reading_file.readlines()
            song_to_be_changed = data[2][:data[2].index(";")]

    with open(file_path, "w") as writing_file:
            writing_file.write("".join(data).replace(song_to_be_changed, new_song))
    with open(file_path, "r") as complete_file:
            print(complete_file.read())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM