繁体   English   中英

Python:创建一个包含文件、路径和内容的元素的字典

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM