简体   繁体   中英

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

The issue I'm facing is that I have to find each file that ends in ".txt" and read it's content to return a dictionary.

Returned dictionary should looks like this:

dic = { 'Folder\\\fileName.txt' : "This is content" }

So far I have:

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 

when I run the program I get None

So far I have gotten this but I don't know how to format it to double quotation and also it's not reading sub directories and foldername file exists on.

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)

Output:

{'.\\foo.txt': 'This is the file content'}

You might want to modify your code a bit.
I suggest you use a recursive function for this, as you would want it to dynamically read all "txt" files in sub-directories as well.
Something like this:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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