我正在迭代具有许多 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