我编写了一个笨重的脚本,将位于一个文件夹中的特定文件移动到三个不同的文件夹中。这三个列表指定应将哪些文件分组并移动到新文件夹。虽然这个脚本有效,但它真的很丑陋且效率低下。如何改进此脚本的结构以帮助使文件移动过程更加优雅和简化?
import os, shutil
# Location of input files
os.chdir = r'C:\path\to\input_imagery'
ws = os.chdir
# Lists of file sets that need to moved
area1 = ["4111201_ne.tif", "4111201_nw.tif"]
area2 = ["4111202_ne.tif", "4111202_nw.tif"]
area3 = ["4111207_nw.tif", "4111301_ne.tif"]
# Output folders
folder_area1 = r'C:\out\area1'
folder_area2 = r'C:\out\area2'
folder_area3 = r'C:\out\area3'
for area in area1:
input1 = os.path.join(ws, area)
output1 = os.path.join(folder_area1, area)
shutil.move(input1, output1)
for area in area2:
input1 = os.path.join(ws, area)
output1 = os.path.join(folder_area2, area)
shutil.move(input1, output1)
for area in area3:
input1 = os.path.join(ws, area)
output1 = os.path.join(folder_area3, area)
shutil.move(input1, output1)
答案 0 :(得分:1)
为什么不把它全部打包
to_move = [
[ 'source_dir1', 'target_dir1', { 'source_file' : 'dest_file', 'source2' : 'dest2'}]
[ 'source_dir2', 'target_dir2', { 'source_file' : 'dest_file', 'source2' : 'dest2'}]
]
然后迭代它。
我为文件使用字典,因为你正在移动它们。这可以保证您的来源在字典中是唯一的。
答案 1 :(得分:1)
也许吧:
import os, shutil
# Location of input files
os.chdir = r'C:\path\to\input_imagery'
ws = os.chdir
filestomove = [
{
'dest': r'C:\out\area1',
'files': ["4111201_ne.tif", "4111201_nw.tif"]
},
{
'dest': r'C:\out\area2',
'files': ["4111201_ne.tif", "4111202_nw.tif"]
}
]
for o in filestomove:
[shutil.move(os.path.join(ws, f),
os.path.join(o['dest'], f)) for f in o['files']]
我认为它清楚明确。