user40720
user40720

Reputation: 89

converting text file to python dictionary

I am having issues converting a text file to a python dictionary. Fortunately, the text file has a ":" that divides my future key with its value. For example, every row is structured like this "-Project Manager: John Caldwell". Id like to loop through a directory that contains numerous text files. In the process id like to strip away a '-' that each row has. Here is the code that i have so far:

import sys, traceback,os, csv, itertools
from collections import defaultdict

def get_metadata(filepath):
    d = defaultdict(list)
    for files in filepath:
        if files.endswith(".txt"):
            with open(files,'r') as in_file:
                for line in in_file:
                    k,v = line.strip('-').split(':')
                    d[k].append(v)

    return d

root_directory = get_metadata("C:\Random")
print root_directory

This is what i get when i run the script

defaultdict(<type 'list'>, {})

Upvotes: 1

Views: 188

Answers (1)

abarnert
abarnert

Reputation: 365717

The problem is that "C:\Random" isn't a list of files, it's just a string. So, for files in filepath gives you 'C', then ':', then '\', and so on. None of those end in .txt, so you don't open any files or do anything else.

What you want is probably for files in os.listdir(filepath):.

Or, if you want to open all files in that directory or any subdirectories (recursively), use walk (see the linked docs for sample code).

As bgporter points out, if the only reason you're calling listdir is to then check each filename against a pattern, you may want to use for files in glob.glob(os.path.join(filepath, '*.txt')): to skip the need for the if test.

Upvotes: 3

Related Questions