Python - ディレクトリを作成して特定のファイルを移動します
-
16-12-2019 - |
質問
Pythonの学習と理解PlayListをダウンロードし、特定のディレクトリにすべてのFLVビデオを移動するYouTube-DLに基づいてスクリプトを作成したいです。
これまでのコードです:
import shutil
import os
import sys
import subprocess
# Settings
root_folder = 'C:/Users/Robert/Videos/YouTube/Playlists/$s'
def download():
files = open('Playlists.txt').readlines()
for playlist in files:
p = playlist.split(';')
# Create the directory for the playlist if it does not exist yet
if not os.path.exists (root_folder % p[0]):
os.makedirs(root_folder % p[0])
# Download every single video from the given playlist
download_videos = subprocess.Popen([sys.executable, 'youtube-dl.py', ['-cit'], [p[1]]])
download_videos.wait()
# Move the video into the playlist folder once it is downloaded
shutil.move('*.flv', root_folder % p[0])
download()
.
私のPlaylists.txtの構造は次のようになります:
Playlist name with spaces;http://www.youtube.com/playlist?list=PLBECF255AE8287C0F&feature=view_all
.
私は2つの問題に遭遇します。まず最初に文字列の書式設定が機能しません。
エラーを得ます:
Playlist name with spaces
Traceback (most recent call last):
File ".\downloader.py", line 27, in <module>
download()
File ".\downloader.py", line 16, in download
if not os.path.exists (root_folder % p[0]):
TypeError: not all arguments converted during string formatting
.
誰かが私にその理由を説明しますか?p [0]を印刷するとうまくいっています。
秒、私は正しいshutil.moveコマンドを設定する方法はありません。ダウンロードしたFLVビデオを移動するだけです。どのようにしてそれをフィルタリングできますか?
ありがとうございました!
解決
免責事項:私はWindows
にいませんメインポイントは、 os.path.join()
通信するための
root_folder = 'C:/Users/Robert/Videos/YouTube/Playlists/$s'
.
-
ダブルエスケープバックスラウェアスを使用する必要があります。 -
%s
の代わりに$s
を意味しました。 -
%s
、os.path.join()
パスを接合するためのクロスプラットフォームの方法です。 - [オプション] IMHOバックスレージはより読みやすいです。
だから私はあなたがその行を変更する必要があると言うでしょう:
root_folder = 'C:/Users/Robert/Videos/YouTube/Playlists'
.
または
root_folder = 'C:\\Users\\Robert\\Videos\\YouTube\\Playlists'
.
または
root_folder = r'C:\Users\Robert\Videos\YouTube\Playlists'
.
そして次のようなことをする:
my_path = os.path.join(root_folder, p[0])
if not os.path.exists(my_path):
# ...
.
Windows上では、各ドライブに対して現在のディレクトリがあるため、
os.path.join("c:", "foo")
は、C:
ではなくドライブc:foo
(c:\foo
)上の現在のディレクトリに対するパスを表します。
有用で判断する> spencer rathbun 例、Windows上で取得する必要があります:
>>> os.path.join('C', 'users')
'C\\users'
>>> os.path.join('C:','users')
'C:users'
.
これは、次のいずれかを使用する必要があることを意味します。
>>> os.path.join('C:/', 'users')
'C:\\users'
>>> os.path.join(r'C:\', 'users')
'C:\\users'
. 他のヒント
$記号は文字列の書式設定に有効な文字ではありません。代わりに%を使用します。
root_folder = 'C:/Users/Robert/Videos/YouTube/Playlists/$s'
print root_folder % 'testfolder'
.
を与えます: 'typeError:文字列の書式設定の間にすべての引数が変換されていません'
root_folder = 'C:/Users/Robert/Videos/YouTube/Playlists/%s'
print root_folder % 'testfolder'
.
私に与えます:/ユーザー/ robert /ビデオ/ youtube / Playlists / TestFolder '
所属していません StackOverflow