首页 > 解决方案 > Pytube - 将文件位置更改设置为工作目录

问题描述

我创建了一个将视频转换为 .mp3 的 youtube 下载器。此外,我添加了命名艺术家和歌曲的可能性,并说明文件下载到的目录。

一切正常,但文件总是保存到 Python 的当前工作目录中,而不是保存到选定的路径file_loc中。

我还注意到从 -function 中删除这部分(用于命名文件)downloader会导致 Python 将文件输出到正确的目录中。

global label_artist, label_song
    name = label_artist.get() + " - " + label_song.get()
    print(name)

有人可以帮帮我吗?

import pytube
from   pytube  import YouTube
from   tkinter import *
from   tkinter import filedialog
import os



#-- creating window for input
# window is named "root"
root             = Tk()
root.geometry("500x400")                # sets size of window
root.title("Youtube Videokonvertierer") # sets title window 
root.configure(bg = "white smoke")      # sets background color of window
Label(root, text = "Youtube Videokonvertierer", font = "arial 20 bold").pack()


#-- defining labels and entry fields for customized name of video
label_artist = StringVar()
label_song   = StringVar()

artist_enter = Entry(root,  width = 30,  textvariable = label_artist).place(x =  32,  y = 140) 
song_enter   = Entry(root,  width = 30,  textvariable = label_song  ).place(x =  270, y = 140) 

Label(root, text = "Künstler").place(x = 32,  y = 119)
Label(root, text = "Lied"    ).place(x = 270, y = 119)



#-- creating field to select download location
# checks if "file_loc" is assigned, if so it shows the path otherwise "Bitte Speicherort auswählen" is shown
try:
    text_dir = file_loc
except:
    text_dir = "Bitte Speicherort auswählen"


# create label that shows either "file_loc" or "Bitte Speicherort auswählen"
label_dir = Label(root, text = text_dir)
label_dir.place(x = 32, y = 185)

# function is later executed via button, enables to select file location
def browse_file():
    global file_loc                                      # saves location of file as global variable (to make it accessible in further code)
    file_loc = filedialog.askdirectory()                 # chooses file location
    label_dir.configure(text = file_loc)                 # updates the label with the selected path (https://stackoverflow.com/questions/28303346/how-to-make-a-tkinter-label-update)


# button to select file path, automatically triggers Label() in browse_file function and updates it with the new path
Button(root, text = "Speicherort wählen...", font = "arial 15 bold", bg = "light steel blue", padx = 2, command = browse_file).place(x = 180, y = 210)










#-- creating field to enter youtube link
link = StringVar()                                                                       # creates variable to hold link
Label(root, text = "Link hier einfügen:", font = "arial 15 bold").place(x = 160, y = 60) # labels field to enter link
link_enter       = Entry(root,  width = 70,  textvariable = link).place(x =  32, y = 90) # creates entry field to input link




#-- download from youtube
def downloader():
    url             = YouTube( str(link.get()) )
    
    
    video           = url.streams.filter(only_audio = True).first()
    print("Downloading...")
    downloaded_file = video.download(file_loc)          # downloads video from youtube
    base, ext       = os.path.splitext(downloaded_file) # splits file name and file extension
    
    
    global label_artist, label_song
    name = label_artist.get() + " - " + label_song.get()
    print(name)


    new_file        = name + '.mp3'                     # pastes file name and ".mp3" together (converts video file into .mp3 file)
    os.rename(downloaded_file, new_file)                # renames file with ".mp3" label
    print("Done")
    os.system(f"start {os.path.realpath( file_loc )}")  # opens file location after video was downloaded and saved as mp3
                                                        # inside of os.system() is path outputted 
    
    
  
    
Button(root, text = "DOWNLOAD", font = "arial 15 bold", bg = "deep sky blue", padx = 2, command = downloader).place(x = 180, y = 270)

root.mainloop()

标签: pythonfilepathlocationpytube

解决方案


问题是你new_file没有创建file_loc

...并且因为os.rename如果您在源路径和目标路径中使用不同的文件夹,可以将文件移动到其他文件夹。

代码video.download(file_loc)将文件下载到预期的文件夹file_loc,但是当您运行时os.rename(downloaded_file, new_file)没有new_name并将file_locrename移动到当前工作目录。

你应该创建

new_file = os.path.join(file_loc, name + '.mp3')

如果你使用,你会看到这个问题

 print(downloaded_file)
 print(new_file)

downloaded_file会有/full/path/to/file_loc/movie.mp4
new_file只会有artist - song.mp3


推荐阅读