Python - 将文件从一个文件夹移动到另一个文件夹但有一些例外

时间:2016-04-29 19:15:19

标签: python

我想将文件从一个文件夹移动到另一个文件夹,但有一些文件异常。一个是特定的文件名,另一个是以AEIOU开头的所有文件夹。我怎么能做到最后一个例外?特定的文件名已经拥有它。感谢。

import os
import shutil

source_dir = "c:/data/abc"
special_dir = "c:/data/zxy"

exclude_files =["file.docx", "file2.xls"]

allfiles = os.listdir(sourcedir)
for each_file in allfiles:
   if each_file not in exclude_files:
      full_path_source_file = os.path.join(source_dir, each_file)
      full_path_target_file = os.path.join(special_dir, each_file)
      shutil.move(full_path_source_file, full_path_target_file)

4 个答案:

答案 0 :(得分:1)

您可以定义自己的Exception并在必要时抛出它。 你的文件夹的一个例子:AEIOU:

class VocalFolder(Exception) :

    def __init__(self, path) :
        self.path = path

    def __str__(self) :
        return repr(self.path) 

假设exclude_files包含以AEIOU开头的文件夹的名称:

try:
    if each_file not in exclude_files:
        ## do your stuff here
    else:
        raise VocalFolder(each_file)
except VocalFolder as ex :
    print "Exception:", str(ex)

希望这有帮助。

以同样的方式为文件执行此操作。

答案 1 :(得分:0)

你想要的是这样的:

import os
import shutil

source_dir = "c:/data/abc"
special_dir = "c:/data/zxy"

exclude_files =["file.docx", "file2.xls"]

allfiles = os.listdir(sourcedir)
for each_file in allfiles:
   if each_file not in exclude_files and
      not (os.path.isdir(each_file) and each_file[0] not in 'AEIOU'):
      full_path_source_file = os.path.join(source_dir, each_file)
      full_path_target_file = os.path.join(special_dir, each_file)
      shutil.move(full_path_source_file, full_path_target_file)

如果你想检查它是否是一个元音而不关心你想要做each_file[0].upper() not in 'AEIOU'的情况,那将检查特定情况。

答案 2 :(得分:0)

您可以使用以下功能来帮助完成任务:

您对以AEIOU开头的目录的附加约束可以表示为isdir(path) and name.startswith('AEIOU')。请注意,您必须将完整路径传递给isdir(),但只检查startswith()的名称。因此,您需要在检查之前构建完整路径,并再次单独使用该名称(使用basename())。

但是如果你将所有内容构建到单个if语句中,它就变得非常难以理解了。因此,我建议将其分解为函数:

def is_excluded(path):
    name = basename(path)
    if isfile(path) and name in ["file.docx", "file2.xls"]:
        return True
    if isdir(path) and name.startswith('AEIOU'):
        return True
    return False

然后,if语句中的格式变为if not is_excluded(path)

一切都在一起:

from os.path import basename
from os.path import isdir
from os.path import isfile
import os
import shutil


source_dir = "c:/data/abc"
special_dir = "c:/data/zxy"


def is_excluded(path):
    name = basename(path)
    if isfile(path) and name in ["file.docx", "file2.xls"]:
        return True
    if isdir(path) and name.startswith('AEIOU'):
        return True
    # Or, if you actually want to check for dirs starting with a vovel:
    # if isdir(path) and name[0] in 'AEIOU':
    #    return True
    return False


allfiles = os.listdir(source_dir)
for each_file in allfiles:
    full_path_source_file = os.path.join(source_dir, each_file)
    full_path_target_file = os.path.join(special_dir, each_file)
    if not is_excluded(full_path_source_file):
        shutil.move(full_path_source_file, full_path_target_file)

修改:我刚刚根据您可能想要检查以元音开头的目录的评论来实现,因此单个字符['A', 'E', 'I', 'O', 'U']

如果是这种情况,您的新支票就会变为name[0].lower() in 'aeiou'(不区分大小写)或name[0] in 'AEIOU'(区分大小写)。

答案 3 :(得分:0)

您还可以尝试以下方法:

import os
import shutil

source_dir = "c:/data/abc"
special_dir = "c:/data/zxy"

exclude_files =["file.docx", "file2.xls"]
allfiles = os.listdir(sourcedir) # dirs are also included

for each_file in allfiles:
   full_path_source_file = os.path.join(source_dir, each_file)
   full_path_target_file = os.path.join(special_dir, each_file)

   if os.path.isfile(full_path_source_file):
      if each_file not in exclude_files:
         shutil.move(full_path_source_file, full_path_target_file)
   else: # each_file is a folder
      if not each_file.upper().startswith('AEIOU'):
         shutil.move(full_path_source_file, full_path_target_file)
相关问题