过滤目录中的文件列表

时间:2015-06-01 06:05:19

标签: csv python-3.x

我的目录中有文件,每天都有以下命名约定,希望过滤文件列表以互操作数据。我一直在玩常规,发现很难匹配我想过滤的文件。

import re

fnames = ["JEExport_20150501-20150531_Credit-Balance-Adjustment-Applied_20150531183249.csv",
        "JEExport_20150501-20150531_External-Credit-Balance-Payment_20150531183254.csv",
        "JEExport_20150501-20150531_External-Payment_20150531183251.csv",
        "JEExport_20150501-20150531_Invoice-Item_20150531183255.csv",
        "JEExport_20150501-20150531_Invoice-Item-Adjustment_20150531183304.csv"
        "JEExport_20150501-20150531_Invoice-Item-Adjustment-Tax_20150531183313.csv",
        "JEExport_20150501-20150531_Taxation-Item_20150531183240.csv"]

for element in fnames:    
    m = re.match("[A-Za-z]+\-[A-Za-z]+|-[A-Za-z]+", element)    
    if m == 'Invoice-Item-Adjustment':
        print(element) # do something

1 个答案:

答案 0 :(得分:1)

我认为你不需要正则表达式。这有用吗?

fnames = ["JEExport_20150501-20150531_Credit-Balance-Adjustment-Applied_20150531183249.csv",
        "JEExport_20150501-20150531_External-Credit-Balance-Payment_20150531183254.csv",
        "JEExport_20150501-20150531_External-Payment_20150531183251.csv",
        "JEExport_20150501-20150531_Invoice-Item_20150531183255.csv",
        "JEExport_20150501-20150531_Invoice-Item-Adjustment_20150531183304.csv",
        "JEExport_20150501-20150531_Invoice-Item-Adjustment-Tax_20150531183313.csv",
        "JEExport_20150501-20150531_Taxation-Item_20150531183240.csv"]

for element in fnames:        
    if 'Invoice-Item-Adjustment' in element:
        print(element) # do something

JEExport_20150501-20150531_Invoice-Item-Adjustment_20150531183304.csv
JEExport_20150501-20150531_Invoice-Item-Adjustment-Tax_20150531183313.csv