我正在Windows和Unix路径上工作,并且有一个具有以下结构的zip文件:
Main
prog
srcSample1.sh
srcSample2.sh
ctl
confSample1.txt
confSample2.txt
我必须将文件复制到以下不同路径:
说我在UNIX上的目标根文件夹是a / b / c / root /,那么复制文件后的预期输出应该是:
root
src
srcSample1.sh
srcSample2.sh
conf
confSample1.txt
confSample2.txt
我尝试使用extract()功能,shutil.copy()和开放式写入功能,但是它们都显示出不同的问题。
使用extract()时,将使用namelist()中的值,并且没有更改范围。
使用shutil.copy()时,我无法在zip文件中引用文件,并且失败,没有此类文件错误。
使用extract()方法的代码:
'''python
zipArtifacts = zipfile.ZipFile(zipFilePath, 'r')
zipFileList = zipArtifacts.namelist()
targetDir = functions.getTargetdir(somemappingfile) # Here I get the target mapping so that if its 'prog' the value will be 'src' and so on.
rootTargetDir= pathlib.Path(targetDir['root'])
rootTargetDir.mkdir(parents=True,exist_ok=True)
for artifact in zipFileList:
if artifact.endswith('/'):
print(artifact + " is a directory")
newTargetDir = rootTargetDir
else:
artifactParts = artifact.split('/')
artifactType = artifactParts[1]
temp = '/'.join(artifactParts[2:])
newTargetDir = rootTargetDir / targetDir[artifactType] / temp
zipArtifacts.extract(artifact, newTargetDir)
'''
使用shutil.copy()方法的代码:
'''python
zipArtifacts = zipfile.ZipFile(zipFilePath, 'r')
zipFileList = zipArtifacts.namelist()
targetDir = functions.getTargetdir(somemappingfile) # Here I get the target mapping so that if its 'prog' the value will be 'src' and so on.
rootTargetDir= pathlib.Path(targetDir['root'])
rootTargetDir.mkdir(parents=True,exist_ok=True)
for artifact in zipFileList:
if artifact.endswith('/'):
print(artifact + " is a directory")
else:
artifactParts = artifact.split('/')
artifactType = artifactParts[1]
temp = '/'.join(artifactParts[2:])
newTargetDir = rootTargetDir / targetDir[artifactType] / temp
shutil.copy(os.path.abspath(artifact), newTargetDir)
'''
使用开放式写入方法的代码:
'''python
zipArtifacts = zipfile.ZipFile(zipFilePath, 'r')
zipFileList = zipArtifacts.namelist()
targetDir = functions.getTargetdir(somemappingfile) # Here I get the target mapping so that if its 'prog' the value will be 'src' and so on.
rootTargetDir= pathlib.Path(targetDir['root'])
rootTargetDir.mkdir(parents=True,exist_ok=True)
for artifact in zipFileList:
if artifact.endswith('/'):
print(artifact + " is a directory")
else:
artifactParts = artifact.split('/')
artifactType = artifactParts[1]
temp = '/'.join(artifactParts[2:])
outfile = open(str(rootTargetDir) + '\\' + targetDir[artifactType] + '\\' + temp, 'wb')
outfile.write()
outfile.close()
'''
我没有尝试先提取所有文件,然后将其复制到不同的目标位置。
从zip文件中的文件列表中,我想根据它们的路径将它们写入输出目录。也就是说,并非所有文件都必须提取到单个目录中,但是目标路径可以更改。