【发布时间】:2019-09-05 23:35:35
【问题描述】:
我有一些文件分散在一个目录中的许多不同文件夹中,我想知道是否有办法以块的形式遍历这些文件夹。
Here's a picture of my directory tree
我想浏览我的 2010A 文件夹中的所有文件,然后是 2010B 文件夹,然后移动到 2011A 和 2011B 等。
我的目标是修改我当前的脚本,该脚本仅适用于单个文件夹,以便它像这样流动:
开始:根文件夹>
2010 > 2010A >
输出到 csv> 重新开始循环 >
2010B > 在最后一行后追加 csv
重新开始循环 > 2011 > 2011A >
在最后一行后追加 csv > 以此类推...
这可能吗?
这是我的代码,如果我在包含我的 txt 文件的单个文件夹上运行它,它目前可以工作,例如,对于 2010A 文件夹:
import re
import pandas as pd
import os
from collections import Counter
#get file list in current directory
filelist = os.listdir(r'root_folder\2010\2010A')
dict1 = {}
#open and read files, store into dictionary
for file in filelist:
with open(file) as f:
items = f.read()
dict1[file] = items
#create filter for specific words
filter = [ "cat", "dog", "elephant", "fowl"]
dict2 = {}
# count occurrence of words in each file
for k, v in dict1.items():
list= []
for i in filter:
list.extend(re.findall(r"{}".format(i),v))
dict2[k] = dict(Counter(new))
dict3 ={}
# count total words in each file, store in separate dictionary
dict3 = {k: {'total':len(v)} for k,v in dict1.items()}
join_dict = {}
#join both dictionaries
join_dict = {k:{**dict2[k], **dict3[k]} for k in out}
#convert to pandas dataframe
df = pd.DataFrame.from_dict(join_dict, orient='index').fillna(0).astype(int)
#output to csv
df.to_csv(r'path\output.csv',index = True, header=True)
我有一种需要更换的感觉:
for file in filelist:
for (root,dirs,files) in os.walk(r'root_folder', topdown=True):
但我不太确定如何,因为我对编码和 python 很陌生。
【问题讨论】:
标签: python-3.x pandas export-to-csv os.walk