python如何移动指定文件_如果python中有特定的文件类型,则移动文件并创建目录...

这可能是一个简单的问题,但我对python和编程基本上还是个新手。

我正在开发一个简单的程序,在镜像源位置的目录结构时将.mp3文件从一个位置复制/移动到另一个位置。到目前为止,我所拥有的工作,但它也在目标位置创建新文件夹,即使源文件夹不包含mp3文件。我只想在源文件包含.mp3的情况下创建新目录,否则可能会导致目标文件中出现一堆空文件夹。

以下是我目前掌握的情况:import os

import shutil #Used for copying files

##CONFIG

source_dir = "C:\Users\username\Desktop\iTunes\\" #set the root folder that you want to scan and move files from. This script will scan recursively.

destPath = "C:\Users\username\Desktop\converted From iTunes" #set the destination root that you want to move files to. Any non-existing sub directories will be created.

ext = ".mp3" #set the type of file you want to search for.

count = 0 #initialize counter variable to count number of files moved

##

##FIND FILES

for dirName, subdirList, fileList in os.walk(source_dir):

#set the path for the destination folder(s)

dest = destPath + dirName.replace(source_dir, '\\')

#if the source directory doesn't exist in the destination folder

#then create a new folder

if not os.path.isdir(dest):

os.mkdir(dest)

print('Directory created at: ' + dest)

for fname in fileList:

if fname.endswith(ext) :

#determine source & new file locations

oldLoc = dirName + '\\' + fname

newLoc = dest + '\\' + fname

if os.path.isfile(newLoc): # check to see if the file already exists. If it does print out a message saying so.

print ('file "' + newLoc + fname + '" already exists')

if not os.path.isfile(newLoc): #if the file doesnt exist then copy it and print out confirmation that is was copied/moved

try:

shutil.move(oldLoc, newLoc)

print('File ' + fname + ' copied.')

count = count + 1

except IOError:

print('There was an error copying the file: "' + fname + '"')

print 'error'

print "\n"

print str(count) + " files were moved."

print "\n"

因此,如果文件夹结构类似于:root->

band 1->

album name->

song.m4a,

song2.m4a

现在它将在目标驱动器中创建所有这些文件夹,即使没有.mp3要复制。。。。。

感谢您的帮助!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值