根据文件名仅提取最新文件

时间:2019-05-03 13:23:35

标签: python max filenames

我只想从已更新的文件中解压缩最新文件。这是我的代码:


def main():

    dest_dir = 'C:/Users/PycharmProjects/kpi/flats'
    zip_file = 'Z:/OUT.zip'

    with ZipFile(zip_file) as zipObj:
        for zip_info in zipObj.infolist():
            if zip_info.filename[-1] == '/':
                continue
            if zip_info.filename.startswith('homeware/R2D2/DATA/OUT/Flat/FlatFile_r2d2_01012018'):
                print(zip_info.filename)
                zip_info.filename = os.path.basename(zip_info.filename)
                zipObj.extract(zip_info,dest_dir)

提取的文件为:

homeware/R2D2/DATA/OUT/Flat/Flat_01012018_180216.csv
homeware/R2D2/DATA/OUT/Flat/Flat_01012018_210147.csv
homeware/R2D2/DATA/OUT/Flat/Flat_01012018_230148.csv

但是我只希望最后一个基于文件名而不是元数据

1 个答案:

答案 0 :(得分:0)

所以我要做的是代替在每次迭代时都提取文件,而是将满足“ if”要求的文件附加到列表中。然后,我提取了该列表的最大值,这就是我要查找的文件。 这是更新的代码:

def main():

    dest_dir = 'C:/Users/mbelahce040119/PycharmProjects/kpi/flats'
    zip_file = 'Z:/DATA/OUT/COMMON_2018/201810/OUT_201810.zip'

    with ZipFile(zip_file) as zipObj:
        files_sat = list()
        for zip_info in zipObj.infolist():
            if zip_info.filename[-1] == '/':
                continue
            if zip_info.filename.startswith('homeware/R2D2/DATA/OUT/Flat/FlatFile_r2d2_01012018'):
                print(zip_info.filename)
                files_sat.append(zip_info.filename)
                zip_info.filename = os.path.basename(max(files))
        zipObj.extract(max(files_sat), dest_dir)