python - 使用python自动移动文件

标签 python linux python-2.7 python-3.x ubuntu

我正在尝试制作一个 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/

相关文章:

python - Matplotlib 自定义样式默认标题位置

python - 测试安装的 Python 包

linux - Grails 的 JAVA_HOME 问题

java - 如何将 spring-boot war 部署到 debian jetty8

python - 为什么 Parsimonious 以 IncompleteParseError 拒绝我的输入?

python - 如何在 Python 中运行/与 Golang 可执行文件交互?

python - 如何获取访问日志

linux - 为什么在手册页中 getenv MT 是安全的?

用于学习 Django 的 Python 2.7 或 3.3

python - 如何检查输入的字母是否在列表中?