使用python自动移动文件

2024-06-06 03:41:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试制作一个python脚本,它允许我将音乐放入一个大文件夹中,这样当我运行脚本时,它将根据音乐文件的第一部分创建文件夹。所以假设我有一个名为OMFG - Ice Cream.mp3的音乐文件,我希望能够分割每个音乐文件名,这样在这个例子中,Ice Cream.mp3它将把它切掉,然后它将使用OMFG来创建一个名为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]

我的主要问题是如何遍历字符串中的每个对象。在

谢谢, 亚历克斯


Tags: path脚本文件夹音乐os文件名mp3例子
2条回答

使用^{} 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

示例:

^{pr2}$

它将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()))

相关问题 更多 >