[英]Python: create a dictionary with elements consist of file, path and the content
我面臨的問題是我必須找到每個以“.txt”結尾的文件並讀取它的內容以返回字典。
返回的字典應如下所示:
dic = { 'Folder\\\fileName.txt' : "This is content" }
到目前為止,我有:
directory = os.path.join("C:/Users/John/Desktop/Ppractice")
rootdir = directory.rstrip(os.sep)
for path, dirs, files in os.walk(rootdir):
folders = path[start:].split(os.sep)
for file in files:
if file.endswith(".txt"):
f=open(os.path.join(subdir, file),'r')
a = f.read()
parent = reduce(dict.get, folders[:-1], dir)
print dir
當我運行程序時,我得到None
到目前為止,我已經得到了這個,但我不知道如何將它格式化為雙引號,而且它也沒有讀取子目錄和文件夾名稱文件。
import os
from os.path import join
def getFileContent(path_dir):
return_Dict = {}
for root, dirs, files in os.walk(path_dir):
for file in files:
if file.endswith(".txt"):
if root in path_dir:
f=open(os.path.join(root, file),'r')
content = (f.read())
f.close()
return_Dict[f.name] = content
return return_Dict
dic = getFileContent(path_dir = "." ) # dot represents a current directory
print (dic)
輸出:
{'.\\foo.txt': 'This is the file content'}
您可能想稍微修改一下代碼。
我建議您為此使用遞歸函數,因為您希望它也動態讀取子目錄中的所有"txt"
文件。
像這樣的東西:
from pprint import pprint
def getFileContent(path_dir, dict_In):
for path, dirs, files in os.walk(path_dir):
folders = path.split(os.sep)
for dir in dirs:
inner_path = path + '/' + dir
getFileContent(inner_path, dict_In)
for file in files:
if file.endswith(".txt"):
f=open(os.path.join(path, file),'r')
content = f.read()
dict_In[f.name] = content
path = os.path.join("C:/Users/John/Desktop/Ppractice")
result_dict = {}
getFileContent(path_dir = path, dict_In = result_dict)
pprint(result_dict)
import os
from os.path import join
def getFileContent(path_dir):
return_Dict = {}
for root, dirs, files in os.walk(path_dir):
for file in files:
if file.endswith(".txt"):
f=open(os.path.join(root, file),'r')
content = (f.read())
f.close()
return_Dict["\\\\".join(f.name[3:].split("\\"))] = content
return ('{%s}' % ', '.join(['"%s": "%s"' % (k, v) for k, v in return_Dict.items()]))
dic = getFileContent(path_dir = "..\\PracPython" )
print (dic)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.