python 压缩文件夹不全_关于子目录:Python压缩子文件夹而不是整个文件夹路径...

我有一个程序来压缩文件夹中的所有内容。 我没有写这个代码,但我发现它在网上某处,我正在使用它。 我打算压缩一个文件夹,比如说C:/ folder1 / folder2 / folder3 /。 我想将folder3及其所有内容压缩到一个文件中说folder3.zip。 使用下面的代码,一旦我压缩它,folder3.zip的内容将是folder1 / folder2 / folder3 /和files。 我不希望整个路径被压缩,我只想让我感兴趣的子文件夹zip(在这种情况下为folder3)。 我尝试了一些os.chdir等,但没有运气。

def makeArchive(fileList, archive):

"""

'fileList' is a list of file names - full path each name

'archive' is the file name for the archive with a full path

"""

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):

# Creates a list of all files in the folder

'''Return a list of file names found in directory 'dir_name'

If 'subdir' is True, recursively access subdirectories under 'dir_name'.

Additional arguments, if any, are file extensions to match filenames. Matched

file names are added to the list.

If there are no additional arguments, all files found in the directory are

added to the list.

Example usage: fileList = dirEntries(r'H:\TEMP', False, 'txt', 'py')

Only files with 'txt' and 'py' extensions will be added to the list.

Example usage: fileList = dirEntries(r'H:\TEMP', True)

All files and all the files in subdirectories under H:\TEMP will be added

to the list. '''

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

你可以用makeArchive(dirEntries(folder, True), zipname)来调用它。

关于如何解决这个问题的任何想法? 我正在使用Windows操作系统和python 25,我知道在python 2.7中有shutil make_archive这有帮助但是因为我正在使用2.5我需要另一种解决方案: - /

您必须为使用相对路径的ZipFile.write()提供arcname参数。通过提供删除到makeArchive()的根路径来执行此操作:

def makeArchive(fileList, archive, root):

"""

'fileList' is a list of file names - full path each name

'archive' is the file name for the archive with a full path

"""

a = zipfile.ZipFile(archive, 'w', zipfile.ZIP_DEFLATED)

for f in fileList:

print"archiving file %s" % (f)

a.write(f, os.path.relpath(f, root))

a.close()

并称之为:

makeArchive(dirEntries(folder, True), zipname, folder)

我已经删除了毯子try:,except:;这里没有用处,只能隐藏你想知道的问题。

os.path.relpath()函数返回相对于root的路径,从而有效地从归档条目中删除该根路径。

在python 2.5上,relpath函数不可用;对于此特定用例,以下替换将起作用:

def relpath(filename, root):

return filename[len(root):].lstrip(os.path.sep).lstrip(os.path.altsep)

并使用:

a.write(f, relpath(f, root))

请注意,上述relpath()函数仅适用于filepath保证以root开头的特定情况;在Windows上,relpath()的一般情况要复杂得多。你真的想要尽可能升级到Python 2.6或更新版本。

我试过这个方法,但因为我使用2.5我不认为我可以使用relpath。我收到此消息:文件"C: Python25 example fullzipnew.py",第14行,在makeArchive a.write(f,os.path.relpath(f,root))中AttributeError:'module'对象没有属性'relpath'

@kraxter:确实,2.6中添加了os.path.relpath()。为什么不升级你的python版本? 2.5现在很老了。

我知道: - /但是现在我正在研究2.5,你认为还有其他的工作吗? :'(

@kraxter:我已经更新了我的答案,为您的具体案例提供解决方案。

谢谢你的解决方案。它只是按照我想要的方式工作。我知道我需要从2.5升级。不久! :)

这正是我想要的

ZipFile.write有一个可选参数arcname。用它来删除部分路径。

您可以将方法更改为:

def makeArchive(fileList, archive, path_prefix=None):

"""

'fileList' is a list of file names - full path each name

'archive' is the file name for the archive with a full path

"""

try:

a = zipfile.ZipFile(archive, 'w', zipfile.ZIP_DEFLATED)

for f in fileList:

print"archiving file %s" % (f)

if path_prefix is None:

a.write(f)

else:

a.write(f, f[len(path_prefix):] if f.startswith(path_prefix) else f)

a.close()

return True

except: return False

不过,Martijn使用os.path的方法要优雅得多。

哦,你是对的,会解决这个问题。

现在,如果path_prefix没有以斜杠结尾,则可以在arcname的开头处使用路径分隔符。

我知道 - 因此我推荐了你的方法。

我尝试过这种方法,这也是一样的。谢谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值