我正在迭代具有许多csv文件的目录结构,我只对该目录中的一些csv文件感兴趣:
if os.path.exists(lang_dir):
dirs = os.listdir(lang_dir)
for filename in dirs:
if re.search(r'-.+-template-users-data.csv$',filename):
但由于某种原因,文件名zu-en-template-users-data.csv
无法识别,我感觉文件名中的字母u
与之有关。只是仔细检查上面的代码段,我直接去了文件夹并用python解释器试了一下,并且python解释器文件确实被正确识别了。
>>> import re
>>> import os
>>> dirs = os.listdir("PATH_FOR_THE_DIR/Data/2013_03_06_20_34/zu")
>>> for item in dirs:
... if re.search(r'-.+-template-users-data.csv$',item):
... print item
...
zu-ab-template-users-data.csv
zu-ace-template-users-data.csv
zu-af-template-users-data.csv
zu-ak-template-users-data.csv
zu-als-template-users-data.csv
...
正如您所见,所有以zu
开头的文件都出现了..这意味着我的正则表达式代码段是正确的? (根据我的理解)
这是我的代码:
def templateUserCountStats(root_dir_path, lang_code_file_path):
#dictionary to hold the template count data structure
template_count_dict = dict()
# getting lang codes from csv file
for lang in getLanguageCodes(lang_code_file_path):
# root level key of the dictionary
template_count_dict[lang] = dict()
lang_dir = os.path.join(root_dir_path, lang)
# get all the files as s list in lang dir
if os.path.exists(lang_dir):
dirs = os.listdir(lang_dir)
for filename in dirs:
if re.search(r'-.+-template-users-data.csv$',filename):
lang2 = filename.split("-")[1]
#path = os.path.join(lang_dir, filename)
path = os.path.expanduser(lang_dir + '/' + filename)
#with open(path, 'rb') as template_user_data_file:
try:
template_user_data_file = open(path, 'r')
try:
csv_file_reader = csv.reader(template_user_data_file)
csv_file_reader.next()
# initializing user count for each language
template_count_dict[lang][lang2] = dict()
template_count_dict[lang][lang2]['level1'] = 0
template_count_dict[lang][lang2]['level2'] = 0
template_count_dict[lang][lang2]['level3'] = 0
template_count_dict[lang][lang2]['level4'] = 0
template_count_dict[lang][lang2]['level5'] = 0
template_count_dict[lang][lang2]['levelN'] = 0
#print filename
for row in csv_file_reader:
if row[0] == '1':
template_count_dict[lang][lang2]['level1'] = template_count_dict[lang][lang2]['level1'] + 1
if row[0] == '2':
template_count_dict[lang][lang2]['level2'] = template_count_dict[lang][lang2]['level2'] + 1
if row[0] == '3':
template_count_dict[lang][lang2]['level3'] = template_count_dict[lang][lang2]['level3'] + 1
if row[0] == '4':
template_count_dict[lang][lang2]['level4'] = template_count_dict[lang][lang2]['level4'] + 1
if row[0] == '5':
template_count_dict[lang][lang2]['level5'] = template_count_dict[lang][lang2]['level5'] + 1
if row[0] == 'N':
template_count_dict[lang][lang2]['levelN'] = template_count_dict[lang][lang2]['levelN'] + 1
except csv.Error, e:
print e
except Exception, e:
print e
logging.error(e)
else:
print "path doesn't exist"
return template_count_dict
答案 0 :(得分:4)
这是因为正则表达式如何将u解释为模式......?
不,这不是原因。
>>> bool(re.search(r'-.+-template-users-data.csv$', 'zu-en-template-users-data.csv'))
True
您的重新模式应该有效,问题出在其他地方。