You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spotipy运行报错无法写入.cache缓存 每次请求重开授权页且文件不写入

问题解决方案
  • 核心问题根因:你在非PyCharm环境运行时,工作目录不匹配或当前目录无写入权限,导致Spotipy无法写入.cache缓存文件存储授权token、也无法写入自定义的txt文件,每次请求都会触发重新授权流程。PyCharm运行时默认使用项目根目录作为工作目录,且有该目录的读写权限,所以运行正常。

修复步骤

  1. 显式指定所有文件的绝对路径:引入os模块获取当前脚本所在的目录,所有读写文件都基于该目录拼接绝对路径,避免工作目录变动导致的路径错误。
  2. 给SpotifyOAuth显式指定缓存文件的绝对路径,解决token缓存写入失败的问题。

修复后代码示例

import os
from spotipy.oauth2 import SpotifyOAuth
import spotipy
import time

# 获取当前脚本所在目录的绝对路径
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))

# 所有文件路径都拼接为绝对路径
file_time_playing = os.path.join(SCRIPT_DIR, "time_playing.txt")
file_time_playing_ms = os.path.join(SCRIPT_DIR, "time_playing_ms.txt")
file_time_total = os.path.join(SCRIPT_DIR, "time_total.txt")
file_time_total_ms = os.path.join(SCRIPT_DIR, "time_total_ms.txt")
cache_path = os.path.join(SCRIPT_DIR, ".cache")
song_path = os.path.join(SCRIPT_DIR, "song.txt")


sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id = ".......",
                                              client_secret = ".......",
                                              redirect_uri = "http://localhost:8080",
                                              scope = "streaming",
                                              cache_path=cache_path)) # 显式指定缓存路径


song = ""

def play_time():
    # 补充你原有的play_time函数逻辑即可
    pass

def track():
   print("======================")
   global song
   global currently_playing

   try:
       currently_playing = sp.currently_playing()
       if song == str(currently_playing["item"]["name"]):
           print(song)
           play_time()
           return
       else:
           song = str(currently_playing["item"]["name"])
           print(song)

           with open(song_path, "w", encoding="utf-8") as f:
               f.write(song)
   except:
       pass


starttime = time.time()
while True:
   track()
   time.sleep(0.5 - ((time.time() - starttime) % 0.5))
  • 额外排查点:如果修改后仍有写入失败问题,确认脚本存放目录不是系统级受保护目录(比如Windows的C:\Program Files、macOS的/System目录),将脚本迁移到普通用户可读写的目录(如桌面、个人用户文件夹)即可。

内容的提问来源于stack exchange,提问作者acidchu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 15:15:00