[英]Automatically move files with python
我正在嘗試創建一個python腳本,允許我將音樂放入一個大文件夾中,這樣當我運行腳本時,它將根據音樂文件的第一部分創建文件夾。 所以,假設我有一個名為OMFG - Ice Cream.mp3
的音樂文件OMFG - Ice Cream.mp3
我希望能夠將每個音樂文件名拆分,以便代替OMFG - Ice Cream.mp3
它會在這種情況下Ice Cream.mp3
它Ice Cream.mp3
和那么它將使用OMFG
創建一個名為that的文件夾。 在創建該文件夾之后,我想找到一種方法然后將OMFG - Ice Cream.mp3
到剛創建的文件夾中。
到目前為止,這是我的代碼:
import os
# path = "/Users/alowe/Desktop/testdir2"
# os.listdir(path)
songlist = ['OMFG - Ice Cream.mp3', 'OMFG - Hello.mp3', 'Dillistone - Sad & High.mp3']
teststr = str(songlist)
songs = teststr.partition('-')[0]
print ''.join(songs)[2:-1]
我的主要麻煩是如何遍歷字符串中的每個對象。
謝謝,亞歷克斯
使用pathlib
模塊進行此類任務很方便:
#!/usr/bin/env python3
import sys
from pathlib import Path
src_dir = sys.argv[1] if len(sys.argv) > 1 else Path.home() / 'Music'
for path in Path(src_dir).glob('*.mp3'): # list all mp3 files in source directory
dst_dir, sep, name = path.name.partition('-')
if sep: # move the mp3 file if the hyphen is present in the name
dst_dir = path.parent / dst_dir.rstrip()
dst_dir.mkdir(exist_ok=True) # create the leaf directory if necessary
path.replace(dst_dir / name.lstrip()) # move file
例:
$ python3.5 move-mp3.py /Users/alowe/Desktop/testdir2
它將OMFG - Ice Cream.mp3
移動到OMFG/Ice Cream.mp3
。
如果你想將OMFG - Ice Cream.mp3
移動到OMFG/OMFG - Ice Cream.mp3
:
#!/usr/bin/env python3.5
import sys
from pathlib import Path
src_dir = Path('/Users/alowe/Desktop/testdir2') # source directory
for path in src_dir.glob('*.mp3'): # list all mp3 files in source directory
if '-' in path.name: # move the mp3 file if the hyphen is present in the name
dst_dir = src_dir / path.name.split('-', 1)[0].rstrip() # destination
dst_dir.mkdir(exist_ok=True) # create the leaf directory if necessary
path.replace(dst_dir / path.name) # move file
您可以嘗試以下代碼:
循環遍歷列表
import os
import shutil
songlist = ['OMFG - Ice Cream.mp3', 'OMFG - Hello.mp3', 'Dillistone - Sad & High']
m_dir = '/path/mainfolder'
song_loc = '/path/songlocation'
for song in songlist:
s = song.split('-')
if os.path.exists(os.path.join(m_dir,s[0])):
shutil.copy(os.path.join(song_loc,song),os.path.join(m_dir,s[0].strip()))
else:
os.makedirs(os.path.join(m_dir,s[0]))
shutil.copy(os.path.join(song_loc,song),os.path.join(m_dir,s[0].strip()))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.