python - 没有完整路径的归档文件

时间:2014-11-06 00:49:11

标签: python

我有以下脚本 -

import os
import stat
import zipfile
from datetime import datetime, timedelta
import logging

logfile = 'D:\\logfiles\\MasterLogsArchive\\archive.log'
logging.basicConfig(filename=logfile, format='%(asctime)s %(message)s', level=logging.DEBUG)

try:
    import zlib
    compression = zipfile.ZIP_DEFLATED
except:
    compression = zipfile.ZIP_STORED

modes = { zipfile.ZIP_DEFLATED: 'deflated',
          zipfile.ZIP_STORED:   'stored',
          }

def modified_date(filename):
    return datetime.fromtimestamp(os.stat(filename)[stat.ST_MTIME])

def find_between( s, first, last ):
    try:
        start = s.index( first ) + len( first )
        end = s.index( last, start )
        return s[start:end]
    except ValueError:
        return ""

move_date = datetime.now() - timedelta(minutes = 2)
src = "D:\\program files (x86)\\TIDAL\\Scheduler\\Master\\log"


for filename in os.listdir(src):
    full_filename = os.path.join(src, filename)
    scheduler = os.path.join(src, 'scheduler.out')

    if modified_date(full_filename) < move_date and filename.startswith('Master'):
        filedate = find_between(filename, '-', '.')[:-7]
        date = filedate[:-2]
        year = filedate[:-6]
        month = filedate[4:-4]
        day = filedate[6:-2]
        hour = filedate[8:]
        dest = "D:\\logfiles\\MasterLogsArchive\\" + date 
        if not os.path.exists(dest):
            os.makedirs(dest)
        zf = dest + '\\' + 'Master%s%s%s-%s.zip' % (year, month, day, hour)

        ## add Master Logs
        if (os.path.isfile(full_filename)):
            if (os.path.isfile(zf)):
                try:
                    logging.info('%s is archived' % full_filename)
                    zip = zipfile.ZipFile(zf, mode='a')
                    zip.write(full_filename, compress_type=compression)
                    os.remove(full_filename)
                finally:
                    zip.close()
            else:
                try:
                    logging.info('%s is archived' % full_filename)
                    zip = zipfile.ZipFile(dest + '\\' + 'Master%s%s%s-%s.zip' % (year, month, day, hour), mode='w')
                    zip.write(full_filename, compress_type=compression)
                    os.remove(full_filename)
                finally:
                    zip.close()

我遇到的问题是,在压缩过程中它正在完成我不想要的完整路径。我只想要zip文件。如果我将zip.write更改为&#39; filename&#39;而不是&#39; full_filename&#39;它然后抱怨它无法找到该文件。

那么如何让写入知道从哪个文件夹中获取文件?

1 个答案:

答案 0 :(得分:0)

实际写入需要更改为以下内容 -

zip.write(full_filename, os.path.basename(full_filename), compress_type=compression)

从这里得到答案 -

How can I zip file with a flattened directory structure using Zipfile in Python?