您可以使用下列功能,以帮助你的任务:
你开始与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'
(区分大小写)。
'os.path.isdir(each_file),而不是each_file.startswith( 'AEIOU')' – taras
此行应该来之前,如果对不对?谢谢 – Gonzalo
@ user128285'isdir()'需要传递完整路径(除非'source_dir'碰巧是当前工作目录)。 –