簡體   English   中英

使用python自動移動文件

[英]Automatically move files with python

我正在嘗試創建一個python腳本,允許我將音樂放入一個大文件夾中,這樣當我運行腳本時,它將根據音樂文件的第一部分創建文件夾。 所以,假設我有一個名為OMFG - Ice Cream.mp3的音樂文件OMFG - Ice Cream.mp3我希望能夠將每個音樂文件名拆分,以便代替OMFG - Ice Cream.mp3它會在這種情況下Ice Cream.mp3Ice 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM