如何简化文件移动脚本?

2024-09-28 22:25:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个笨拙的脚本,将位于一个文件夹中的特定文件移动到三个不同的文件夹中。这三个列表指定哪些文件应分组并移动到新文件夹。虽然这个脚本可以工作,但它确实是丑陋和低效的。如何改进此脚本的结构,使文件移动过程更加优雅和精简?你知道吗

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)

Tags: path脚本文件夹wsosareafolderjoin
2条回答

也许是:

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']] 

我认为这是明确和明确的。你知道吗

为什么不打包呢

to_move = [
  [ 'source_dir1', 'target_dir1', { 'source_file' : 'dest_file', 'source2' : 'dest2'}]
  [ 'source_dir2', 'target_dir2', { 'source_file' : 'dest_file', 'source2' : 'dest2'}]
  ]

然后再重复一遍。你知道吗

我用字典来查找这些文件,因为你正在移动它们。这保证了你的来源在dict中是唯一的

相关问题 更多 >