我正在尝试制作一个 python 脚本,它允许我将音乐放入一个大文件夹中,因此当我运行该脚本时,它将根据音乐文件的第一部分创建文件夹。假设我有一个名为 OMFG - Ice Cream.mp3
的音乐文件,我希望能够拆分每个音乐文件名,而不是 OMFG - Ice Cream.mp3
在这种情况下,它会将其切掉 Ice Cream.mp3
,然后它会使用 OMFG
创建一个名为该文件夹的文件夹。创建该文件夹后,我想找到一种方法,然后将其移动到刚创建的文件夹中。
到目前为止,这是我的代码:
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
module for such tasks :
#!/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
关于python - 使用python自动移动文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33227556/