Q:

Storing files as list and reading data from them in python

I was wondering if I had a directory full of similar .txt files, if there was a way to store these as a list of lists in python, iterate through the list to open the files, and then iterate through the objects in the file to achieve something. For example:
ls /Path/to/directory/
1.txt 2.txt 3.txt 4.txt

the contents of each file would be like:
more 1.txt
1
2
3
4

For the python script something like:
import os
pathname = os.path.join("directory",filenames)
for i in pathname:
    file_open = open(pathname[i])
    for j in file_open:
        file_sum = sum(int[j])
    return file_sum

or would it just be better to do this with a shell script to run the python command for each file individually and write output to file? I just wanted to see if there was a cool pythonic way to do this.
#!/bin/bash

RUN_PATH=$1; shift
cd $RUN_PATH

for file in $RUN_PATH*
do
    MONEY=`basename $file`
    BAG=`python my_script.py $file`
    echo $MONEY "      " $BAG >> money_bag.txt
done;

thanks for the help

A:

Yes. We can use a combination of glob (to get all of the text files), a short function and a dictionary comprehension:
import glob

def sum_file(file_path):
    total = 0
    with open(file_path, 'r') as f:
        for line in f:
            try:
                total += int(line)
            except ValueError:
                continue
    return total

folder_location = r'path\to\directory\*.txt'

file_sums = {p: sum_file(p) 
             for p in glob.glob(folder_location)}

file_sums will be a dictionary where the keys are the paths to each file, and the values the total of all lines that can be interpreted as integers in those files.

