Search code examples
pythonbashlistglob

Read the contents of each file into a separate list in Python


I would like to ready the contents of each file into a separate list in Python. I am used to being able to do something similar with a bash for loop where I can say:

for i in file_path; do writing stuff; done

With glob I can load each of the files but I want to save the contents in a list for each file to use them for comparison purposes later without hardcoding the names and number of lists. This is how far I have gotten in python:

import sys
import glob
import errno

list_$name[] ##<this is not python

path = './dir_name/*'   
files = glob.glob(path)   
for name in files:
    try:
        with open(name) as f:
            lines = f.read().splitlines()


    except IOError as exc:
        if exc.errno != errno.EISDIR:
            raise

Is what I want to do even possible or do I have to use a shell script to process each file as a loop?


Solution

  • import sys
    import glob
    import errno
    
    list_$name[] ##<this is not python
    
    path = './dir_name/*'   
    files = glob.glob(path)
    
    contents = []   
    for name in files:
        try:
            with open(name) as f:
                lines = f.read().splitlines()
                contents.append (lines)
    
    
        except IOError as exc:
            if exc.errno != errno.EISDIR:
                raise
    
        # Your contents list will now be a list of lists, each list containing the contents of one file.