如何从 Spotipy 获取歌曲列表,然后将它们保存到 txt 文件?

How to get list of songs from Spotipy and then save them to a txt file?

我一直在尝试使用在 Spotify 上创建一个艺术家的前 10 首歌曲列表(使用 Spotipy),然后将这些歌曲保存到列表中的 txt 文件,但我不知道如何做.对不起,如果它太明显了!

我也希望能够将这些歌曲放入播放列表中。我已经弄清楚如何创建播放列表,但还不知道如何向其中添加特定歌曲,所以欢迎任何建议!

我的代码是:

import spotipy
import spotipy.util as util
from spotipy.oauth2 import SpotifyOAuth

sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id="",
                                               client_secret="",
                                                          
redirect_uri="http://localhost:8080/"))

# shows tracks from a specific artist
choice = input("What artist's songs do you want some names of? ")

with open('songs.txt', 'r') as song_file:
    contents = song_file.read()

results = sp.search(q=[choice], limit=10)
for idx, track in enumerate(results['tracks']['items']):
    print(idx, track['name'])

with open('songs.txt', 'w+') as song_file:
    song_file.write(contents)

for song in contents:
    song_file.append(float(row['song']))

我没有测试它,但如果你想将新值附加到文件中,那么你不必再次读取和写入它。您可以在 append mode - open(..., "a") 中打开它,然后 write() 将在文件末尾添加文本。

并且当您从服务器获取数据时,您应该 运行 for-在 with open()write 内循环新信息作为带有 \n 的文本到分行

results = sp.search(q=[choice], limit=10)

with open('songs.txt', 'a') as song_file: # open in `append mode`
    for idx, track in enumerate(results['tracks']['items']):  # run loop inside `with open`
        #print(idx, track['name'])
        song_file.write( f'{idx} {track['name']}\n' )   # write as string and add `\n` to put in separated lines