user1447941
user1447941

Reputation: 3895

How can I get the file names and contents of a whole directory?

I have a directory named main that contains two files: a text file named alex.txt that only has 100 as its contents, and another file named mark.txt that has 400.

I want to create a function that will go into the directory, and take every file name and that file's contents and store them (into a dict?). So the end result would look something like this:

({'alex.txt', '100'}, {'mark.txt', '400'})

What would be the best way of doing this for large amounts of files?

Upvotes: 1

Views: 108

Answers (3)

tMC
tMC

Reputation: 19315

import os
bar = {}
[bar.update({i: open(i, 'r').read()}) for i in os.listdir('.')]

or (via mgilson)

bar = dict( (i,open(i).read()) for i in os.listdir('.') )

Upvotes: 1

mgilson
mgilson

Reputation: 309841

This looks like a good job for os.walk

d = {}
for path,dirs,fnames in os.walk(top):
    for fname in fnames:
        visit = os.path.join(path,fname)
        with open(visit) as f:
             d[visit] = f.read()

This solution will also recurse into subdirectories if they are present.

Upvotes: 6

Pierre GM
Pierre GM

Reputation: 20339

Using a dictionary looks like the way to go.

You can use os.listdir to get a list of the files in your directory. Then, iterate on the files, opening each of them, reading its input and storing them in your dictionary.

If your main directory has some subdirectories, you may want to use the os.walk function to process them recursively. Stick to os.listdir otherwise.

Note that an item of os.listdir is relative to main. You may want to add the path to main before opening the file. In that case, use os.path.join(path_to_main, f) where f is an item of os.listdir.

Upvotes: 2

Related Questions