繁体   English   中英

Python研究异常

[英]Python re.search anomaly

我有一个搜索文件目录并从文件名中提取客户编号的例程:

import os
import re

suffix= '.csv'

# For each file in input folder, extract customer number 
input_list = os.listdir(path_in)
for input_file in input_list:
        fileInput = os.path.join(path_in,input_file)
        customer_ID = re.search('custID_(.+?)'+suffix,fileInput).group(1)
        print(customer_ID)

使用suffix='.csv'和一个充满csv文件的文件夹:

avg_hrly_custID_8147611.csv,avg_hrly_custID_8147612.csv,avg_hrly_custID_8147613.csv ...

我得到了预期的输出:

8147611、8147612、8147613 ...

但是, suffix = '.png'和.png图像文件的文件夹:

每年一次_平均_plot_custID_8147611.png,一年一次_平均_plot_custID_8147612.png,一年一次_平均_plot_custID_8147613.png ...

我收到此错误:

AttributeError:'NoneType'对象没有属性'group'

为什么它不适用于图像文件?

@BrenBarn发现了问题的原因。 正则表达式失败,因为目录中有一个子目录名不匹配。 我已经通过引入try....except解决了

import os
import re

suffix= '.png'

# For each file in input folder, extract customer number 
input_list = os.listdir(path_in)
for input_file in input_list:
        fileInput = os.path.join(path_in,input_file)
        try:
           customer_ID = re.search('custID_(.+?)'+suffix,fileInput).group(1)
           print(customer_ID)
        except:
           pass

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM