あなたはあなたの仕事を支援するため、以下の機能を使用することができます。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)及びません( 'AEIOU')をeach_file.startswith' – taras
この行があれば、右の前に来る必要がありますか?ありがとうございます – Gonzalo
@ user128285 'isdir()'はフルパスを渡す必要があります( 'source_dir'が現行の作業ディレクトリでない限り)。 –