Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

Appending data to pickle in python

I am creating a program which generates a random list of songs, and has a function such that if a user wants to save a song from the random generated list, the user should click the button next to it. Then the user can print the songs he/she saved on a new window, and then I add a function using pickle so that if the user closes and reruns the program the previously saved items are retained and can be reprinted. But an error, how can I implement this correctly

This is the code:

from tkinter import *
import tkinter as tk
from PIL import ImageTk, Image
import random
import pickle
from tkinter import messagebox

alternative_music = ['Smells Like Teen Spirit - Nirvana',
                     'Love will tear us apart - Joy Division',
                     'Radio Free Europe - R.E.M.',
                     'Blue Monday - New Order',
                     'How Soon is Now? - The Smiths',
                     'Once in a Lifetime - Talking Heads',
                     'Teen Age Riot - Sonic Youth',
                     'Blister in the Sun - Violent Femmes',
                     'Jeremy - Pearl Jam',
                     'Monkey Gone to Heaven - Pixies',
                     'Under the Bridge - Red Hot Chili Peppers',
                     'Black Hole Sun - Soundgarden',
                     'Closer - Nine Inch Nails',
                     'Losing My Religion - R.E.M.',
                     'Wonderwall - Oasis',
                     'Just like Heaven - The Cure',
                     'Cannonball - The Breeders',
                     'Come As You Are - Nirvana',
                     'Loser - Beck',
                     'Creep - Radiohead',
                     'Bela Lugosis Dead - Bauhaus',
                     'Personal Jesus - Depeche Mode',
                     'Song 2 - Blur',
                     'The Killing Moon - Echo and the Bunnymen',
                     'Sunday Bloody Sunday - U2',
                     'Common People - Pulp',
                     'There Is a Light That Never Goes Out - The Smiths',
                     'Running Up That Hill (A Deal With God) - Kate Bush',
                     'Its The End of the World As We Know It (And I Feel Fine) - R.E.M.',
                     '1979 - The Smashing Pumpkins',
                     'Waiting Room - Fugazi',
                     'Lovesong - The Cure',
                     'Alive - Pearl Jam',
                     'Radio, Radio - Elvis Costello & The Attractions',
                     'All Apologies - Nirvana',
                     'Atmosphere - Joy Division',
                     'Here Comes Your Man - Pixies',
                     'Paranoid Android - Radiohead',
                     f"There She Goes - The La's",
                     'Everlong - Foo Fighters',
                     'Buddy Holly - Weezer',
                     'Plush - Stone Temple Pilots',
                     'Enjoy the Silence - Depeche Mode',
                     'This Charming Man - The Smiths',
                     'Would? - Alice in Chains',
                     'The One I Love - R.E.M.',
                     'Touch Me, Im Sick - Mudhoney',
                     'Head Like a Hole - Nine Inch Nails',
                     'Bastards of Young - The Replacements',
                     'Burning Down the House - Talking Heads']


def show_generated_list():
    global generated_list

    generated_list = []

    if genre.get() == "Alternative Music":
        top = tk.Toplevel()
        top.title(genre.get() +' Play list')
        windowWidth = top.winfo_reqwidth()
        windowHeight = top.winfo_reqheight()
        positionRight = int(top.winfo_screenwidth() / 1.7 - windowWidth / 2)
        positionDown = int(top.winfo_screenheight() / 4 - windowHeight / 2)
        top.geometry("+{}+{}".format(positionRight, positionDown))

        # Info Box
        messagebox.showinfo("You can save the song", "You can save each song 
 by clicking the button beside it")

        for i, title in enumerate(random.sample(alternative_music, k=10)):
            my_label = tk.Label(top, text=title, font=('Garamond ',14),
                                anchor='w', bg="#7dd0b6", highlightbackground='#000000',
                                highlightthickness=10, bd=0, borderwidth=0)
            my_label.grid(column=2, columnspan=2, sticky='we', row=i, pady=2)
            tk.Button(top,
                      text=str(i + 1) + ".",
                      border=5,
                      padx=5,
                      pady=5,
                      command=lambda title=title: generated_list.append(title)
                      ).grid(column=0, row=i)

def show_my_playlist():
    global generated_list
    global my_playlist
    global my_img
    global bg_lbl

    for song in generated_list:
        if song not in my_playlist:
            my_playlist.append(song)


    filename = "my_playlist2.txt"
    with open(filename, 'a+') as fp:
        pickle.dump(my_playlist, fp)
        # pickle.dump(q, fp)

    top = tk.Toplevel()
    top.title('Your Playlist')
    top.geometry("500x500")
    windowWidth = top.winfo_reqwidth()
    windowHeight = top.winfo_reqheight()
    positionRight = int(top.winfo_screenwidth() / 1.7 - windowWidth / 2)
    positionDown = int(top.winfo_screenheight() / 4 - windowHeight / 2)
    top.geometry("+{}+{}".format(positionRight, positionDown))
    my_img = ImageTk.PhotoImage(Image.open("tkimageviewer/imgbg2.png"))
    bg_lbl =Label(top, image=my_img)
    bg_lbl.place(x=0, y=0, relwidth=1, relheight=1)

    data = []
    with open(filename, 'rb') as fr:
        try:
            while True:
                data.append(pickle.load(fr))
        except EOFError:
            pass

    for i, title in enumerate(data):
        my_label = tk.Label(top, text=title, font=("Courier New",14), anchor='w', borderwidth=0)
        my_label.grid(column=2, columnspan=2, sticky='we', row=i, pady=(18,0))




genre_options = [
    "Alternative Music",
    # "Classical and Opera Music",
    # "Country and Folk",
    # "Dance and EDM",
    # "Reggae and R&B/Soul",
    # "Worship and Gospel and New Age",
    # "Pop Music",
    # "Songs people  like to listen to"
]

generated_list = []
my_playlist = []
my_quote_list = []
root = Tk()
root.title('UMIND')
root.iconbitmap('Ricon.ico')
root.geometry('')
root.config(bg='light blue')
windowWidth = root.winfo_reqwidth()
windowHeight = root.winfo_reqheight()
positionRight = int(root.winfo_screenwidth() / 8 - windowWidth / 2)
positionDown = int(root.winfo_screenheight() / 4 - windowHeight / 2)
root.geometry("+{}+{}".format(positionRight, positionDown))
playlist_gen_btn = PhotoImage(file="tkimageviewer/playlis_gen_btn.png")
my_qts_btn = PhotoImage(file="tkimageviewer/my_qts_btn.png")
my_playlist_btn = PhotoImage(file="tkimageviewer/my_playlist_btn.png")
genre = StringVar()
genre.set('From what Genre?')

drop = OptionMenu(root, genre, *genre_options)
drop.grid(row=2, column=0, ipadx=20, ipady=10, padx=15, pady=15)

generate_btn = tk.Button(root, image=playlist_gen_btn, command=show_generated_list, borderwidth=0)
generate_btn.grid(row=2, column=1, padx=15, pady=15)

playlist_btn = tk.Button(root, image=my_playlist_btn, command=show_my_playlist, borderwidth=0)
playlist_btn.grid(row=3, column=0, padx=15, pady=15)


root.mainloop()

This is the error I got:

  File "C:PycharmProjectspythonProjectpicklepractice.py", line 112, in show_my_playlist
    pickle.dump(my_playlist, fp)
TypeError: write() argument must be str, not bytes
question from:https://stackoverflow.com/questions/65660651/appending-data-to-pickle-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
import pickle

lst = [1,2,3]

with open("test.dat", "wb") as msg:
    pickle.dump(lst, msg)

with open("test.dat", "ab+") as msg:
    pickle.dump(lst, msg)

with open("test.dat", "rb") as msg:
    print (pickle.load(msg))

It seems using "ab+" makes it.

Output:

[1, 2, 3]
[1, 2, 3]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...