python import all files in directory code example
Example 1: python import all files in directory
import glob
import os
directory = '/path/to/directory/with/files/'
all_files = glob.glob(os.path.join(directory, "*.txt"))
your_list = [ ]
for filename in all_files:
dataframe = pd.read_csv(filename, index_col=None, header=0, sep="\t")
your_list.append(dataframe)
Example 2: python3 import all files in directory
from inspect import isclass
from pkgutil import iter_modules
from pathlib import Path
from importlib import import_module
package_dir = Path(__file__).resolve().parent
for (_, module_name, _) in iter_modules([package_dir]):
module = import_module(f"{__name__}.{module_name}")
for attribute_name in dir(module):
attribute = getattr(module, attribute_name)
if isclass(attribute):
globals()[attribute_name] = attribute