gpt4 book ai didi

python - 如果 python 中的某些文件类型移动文件和创建目录

转载 作者:太空宇宙 更新时间:2023-11-03 11:54:40 24 4
gpt4 key购买 nike

这可能是一个简单的问题,但我对 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.....

感谢任何帮助!

最佳答案

我想我会为这类事情创建自己的副本包装器:

def fcopy(src,dest):
"""
Copy file from source to dest. dest can include an absolute or relative path
If the path doesn't exist, it gets created
"""
dest_dir = os.path.dirname(dest)
try:
os.makedirs(dest_dir)
except os.error as e:
pass #Assume it exists. This could fail if you don't have permissions, etc...
shutil.copy(src,dest)

现在您可以在任何 .mp3 文件上调用此函数来遍历树。

关于python - 如果 python 中的某些文件类型移动文件和创建目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14887743/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com