python 压缩文件夹不全_Python压缩子文件夹而不是整个文件夹路径

我有一个程序来压缩文件夹中的所有内容。我没有写这段代码,但我在网上找到了它,我正在使用它。我打算压缩一个文件夹,例如,C:/folder1/folder2/folder3/。我想压缩folder3及其文件中的所有内容,如folder3.zip。使用下面的代码,压缩后folder3.zip的内容将是folder1/folder2/folder3/和文件。我不希望整个路径都被压缩,我只希望im感兴趣的子文件夹压缩(在本例中是folder3)。我试过做些手术,但没有成功。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)来调用它。

关于如何解决这个问题有什么想法吗?我使用的是WindowsOS和Python25,我知道Python2.7中有一个shuilmake_存档,这很有帮助,但是由于我在2.5上工作,我需要另一个解决方案:-/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值