我需要帮助编辑以下脚本来压缩目录的内容。我的最终目标是创建一个脚本,它将查看C:\ Test(里面会有多个目录),并在C:\ Test中创建一个包含每个目录内容的新zip文件。棘手的部分是我需要路径为C:\,即使目录的真路径是C:\ Test。这可能还是我在做梦?
由于
import zipfile, os
def makeArchive(fileList, archive):
try:
a = zipfile.ZipFile(archive, 'w', zipfile.ZIP_DEFLATED)
for f in fileList:
print "archiving file %s" % (f)
a.write(f)
a.close()
return True
except: return False
def dirEntries(dir_name, subdir, *args):
fileList = []
for file in os.listdir(dir_name):
dirfile = os.path.join(dir_name, file)
if os.path.isfile(dirfile):
if not args:
fileList.append(dirfile)
else:
if os.path.splitext(dirfile)[1][1:] in args:
fileList.append(dirfile)
# recursively access file names in subdirectories
elif os.path.isdir(dirfile) and subdir:
print "Accessing directory:", dirfile
fileList.extend(dirEntries(dirfile, subdir, *args))
return fileList
if __name__ == '__main__':
folder = r'C:\test'
zipname = r'C:\test\test.zip'
makeArchive(dirEntries(folder, True), zipname)
答案 0 :(得分:0)
您可以按如下方式更改存档内文件的路径:
a.write(PATH_ON_FILESYSTEM,
DESIRED_PATH_IN_ARCHIVE
)