语法
listdir()方法语法格式如下:
os.listdir(path)
path – 需要列出的目录路径
返回值
返回指定路径下的文件和文件夹列表。
例子:
(1)
import os, sys
#打开文件
path = “/var/www/html/”
dirs = os.listdir( path )
#输出所有文件和文件夹
for file in dirs:
print(file)
执行以上程序输出结果为:
test.htm
stamp
faq.htm
_vti_txt
robots.txt
itemlisting
resumelisting
writing_effective_resume.htm
advertisebusiness.htm
例子2:
def import_dict(dictpath):
all_dicts = {}
dict_list = os.listdir(dictpath)
for dict in dict_list:
jieba.load_userdict(dictpath+’/’+dict) # load to jieba
dict_words = []
with open(dictpath+’/’+dict, ‘r’) as f:
for word in f:
dict_words.append(word.strip())
all_dicts[dict[:-4]] = dict_words
return all_dicts