Home > OS >  How can I tell Python to write a comma between tuple values?
How can I tell Python to write a comma between tuple values?

Time:04-06

When I choose some songs this code takes the paths of these songs and writes them to a txt.file:

def create_playlist():

playlist_songs = filedialog.askopenfilenames(initialdir=f'C:/Users/{Playlist.username}/Music',filetypes=[('Audio Dateien','.mp3')])

playlist_file = str(filedialog.asksaveasfile(initialdir=f'C:/Users/{Playlist.username}/Music',filetypes=[('Playlistdatei','.txt')]))
playlist_file = playlist_file[25: playlist_file.index("' ")]
with open (playlist_file, 'w') as file:
    print(playlist_songs)
    file.write lines(playlist_songs)

However, when I look at the output of my txt.file I see that there are missing commas between new paths. On the picture below I have marked, where the red commas in the picture are, there should be an added comma:

https://i.stack.imgur.com/SmD5T.png

How do I accomplish this?

CodePudding user response:

See the following code to read the lines, remove the EOL, and add a comma. Thus placing all on one line separated by commas.

def create_playlist():
    playlist_songs = filedialog.askopenfilenames(
        initialdir=f'C:/Users/{Playlist.username}/Music',
        filetypes=[('Audio Dateien', '.mp3')])

    playlist_file = str(filedialog.asksaveasfile(
        initialdir=f'C:/Users/{Playlist.username}/Music',
        filetypes=[('Playlistdatei', '.txt')]))
    playlist_file = playlist_file[25: playlist_file.index("' ")]

    with open(playlist_songs, 'r') as f_in:
        print(f_in.read())  # Check the contents of playlist_songs
        with open(playlist_file, 'w') as f_out:
            # Write the formatted contents to playlist_file
            for line in f_in:
                # Remove the end of line using line.strip(), and append a comma
                f_out.write(line.strip()   ',')

CodePudding user response:

It's because of the writelines that print each element of the list as line separated by a newline \n, so you can fix this with:

all_songs_in_one_string = ";".join(playlist_songs)
file.write(all_songs_in_one_string)
  • Related