Python 使用批处理将文件和文件夹复制到其他路径
我有一个目录c:/go,里面有很多文件夹、子文件夹和文件 我需要在go内部找到以net*.inf和oem*.inf开头的文件,并将文件夹、子文件夹和所有文件复制到c:/Python 使用批处理将文件和文件夹复制到其他路径,python,windows,vbscript,batch-file,Python,Windows,Vbscript,Batch File,我有一个目录c:/go,里面有很多文件夹、子文件夹和文件 我需要在go内部找到以net*.inf和oem*.inf开头的文件,并将文件夹、子文件夹和所有文件复制到c:/ 它必须是自动使用windows的东西。。。就像批处理脚本,C++,Python…VBS!提前感谢来自命令行的,其中一种方法是结合: 在批处理文件中,只需将%i替换为%i即可。@ars答案中的xcopy技术显然更适合您的情况。然而,下面是一个Python实现。它将确保目标目录存在,如果不存在,则创建它: #!python impo
它必须是自动使用windows的东西。。。就像批处理脚本,C++,Python…VBS!提前感谢来自命令行的,其中一种方法是结合:
在批处理文件中,只需将
%i
替换为%i
即可。@ars答案中的xcopy技术显然更适合您的情况。然而,下面是一个Python实现。它将确保目标目录存在,如果不存在,则创建它:
#!python
import os
import re
import shutil
def parse_dir(src_top, dest_top):
re1 = re.compile("net.*\.inf")
re2 = re.compile("oem.*\.inf")
for dir_path, dir_names, file_names in os.walk(src_top):
for file_name in file_names:
if re.match(re1, file_name) or re.match(re2, file_name):
target_dir = dir_path.replace(src_top, dest_top, 1)
if not os.path.exists(target_dir):
os.mkdir(target_dir)
src_file = os.path.join(dir_path, file_name)
dest_file = os.path.join(target_dir, file_name)
shutil.copyfile(src_file, dest_file)
src_top = "\\go"
dest_top = "\\dest"
parse_dir(src_top, dest_top)
改进可能是可能的,但是如果你想这样做,这应该让你开始 条件目录创建可以简单地用一行代码修改到批处理中。@Joey:是的,这是我引用ars答案的一部分。我只是提供了一个替代方案。。。它也应该在*nix平台上工作(路径分隔符稍微改为/,这将在Windows上工作,但我使用了\使代码看起来更像Windows)。谢谢你,我真的很感激。。。还将尝试使用putjon CodeThankkyu veru much!!我打破了我的头,它最终变得如此简单的代码。。。虽然我尝试从c:go复制到c:go/go2时出错。。。我猜是因为它在源文件夹中。。。有什么想法吗?代码也会复制inf和他各自的文件夹,但如何下载同一文件夹中的其他文件?@masaki:您可以分两步完成:如上所述从c:\go\复制到c:\go2\上,然后将
move
c:\go2\置于c:\go\下。关于你的第二条评论,我不知道你所说的“同一文件夹中的其他文件”是什么意思。还有哪些文件?我是说里面有很多其他文件。。。以及.inf。。。我需要所有其他文件,包括inf。。。但我只想要文件夹中包含.inf文件的所有文件,这些文件包含单词nrt或oem…)所以我想我一定是像xcopy/s\go**。但只适用于inf有“网络”的foldera。。。
#!python
import os
import re
import shutil
def parse_dir(src_top, dest_top):
re1 = re.compile("net.*\.inf")
re2 = re.compile("oem.*\.inf")
for dir_path, dir_names, file_names in os.walk(src_top):
for file_name in file_names:
if re.match(re1, file_name) or re.match(re2, file_name):
target_dir = dir_path.replace(src_top, dest_top, 1)
if not os.path.exists(target_dir):
os.mkdir(target_dir)
src_file = os.path.join(dir_path, file_name)
dest_file = os.path.join(target_dir, file_name)
shutil.copyfile(src_file, dest_file)
src_top = "\\go"
dest_top = "\\dest"
parse_dir(src_top, dest_top)