newWithPython
newWithPython

Reputation: 883

How do I retrieve the contents of all the files in a directory in a list each one?

I would like to read the all the files in a directory so I'm doing the following:

path = '/thepath/of/the/files/*'
files = glob.glob(path)
for file in files:
    print file

The problem is that when I print the files I don't obtain anything; any idea of how to return all the content of the files in a list per file?

EDIT: I appended the path with an asterisk, this should give you all the files and directories in that path.

Upvotes: 0

Views: 69

Answers (3)

Lord Henry Wotton
Lord Henry Wotton

Reputation: 1362

Like in the comment I posted some time ago, this should work:

contents=[open(ii).read() for ii in glob.glob(path)]

or this, if you want a dictionary instead:

contents={ii : open(ii).read() for ii in glob.glob(path)}

Upvotes: 1

MattDMo
MattDMo

Reputation: 102852

Your question is kind of unclear, but as I understand it, you'd like to get the contents of all the files in the directory. Try this:

# ...
contents = {}
for file in files:
    with open(file) as f:
        contents[file] = f.readlines()
print contents

This creates a dict where the key is the file name, and the value is the contents of the file.

Upvotes: 1

Digisec
Digisec

Reputation: 700

I would do something like the following to only get files.

import os
import glob

path = '/thepath/of/the/files/*'
files=glob.glob(path)
for file in files:
    if os.path.isfile(file):
        print file

Upvotes: 1

Related Questions