[英]Python re.search anomaly
I have a routine that searches through a directory of files and extracts a customer number from the filename: 我有一个搜索文件目录并从文件名中提取客户编号的例程:
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)
With suffix='.csv'
and a folder full of csv files: 使用
suffix='.csv'
和一个充满csv文件的文件夹:
avg_hrly_custID_8147611.csv, avg_hrly_custID_8147612.csv, avg_hrly_custID_8147613.csv ...
avg_hrly_custID_8147611.csv,avg_hrly_custID_8147612.csv,avg_hrly_custID_8147613.csv ...
I get the expected output: 我得到了预期的输出:
8147611, 8147612, 8147613...
8147611、8147612、8147613 ...
BUT, with suffix = '.png'
and a folder of .png image files,: 但是,
suffix = '.png'
和.png图像文件的文件夹:
yearly_average_plot_custID_8147611.png, yearly_average_plot_custID_8147612.png, yearly_average_plot_custID_8147613.png ...
每年一次_平均_plot_custID_8147611.png,一年一次_平均_plot_custID_8147612.png,一年一次_平均_plot_custID_8147613.png ...
I get this error: 我收到此错误:
AttributeError: 'NoneType' object has no attribute 'group'
AttributeError:'NoneType'对象没有属性'group'
Why won't it work for image files? 为什么它不适用于图像文件?
@BrenBarn spotted the cause of the problem. @BrenBarn发现了问题的原因。 The regex failed because there was a subdirectory in the directory who's name didn't match.
正则表达式失败,因为目录中有一个子目录名不匹配。 I've solved it by introducing
try....except
我已经通过引入
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.