Python: 创建一个字典,其元素由文件、路径和内容组成

Python: create a dictionary with elements consist of file, path and the content

我面临的问题是我必须找到每个以“.txt”结尾的文件并将其内容读入 return 字典。

返回的字典应该如下所示:

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

您可能需要稍微修改一下代码。
我建议您为此使用递归函数,因为您希望它也动态读取 sub-directories 中的所有 "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"):
                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'}
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)