Python - Read all files from folder (.shp, .dbf, .mxd etc)

user2278713 picture user2278713 · Apr 14, 2013 · Viewed 17.8k times · Source

Can anyone help me? I'm trying to write a code that will read all the files from a data folder. The files all have different extensions: .shp, .dbf, .sbx, .mxd) I'm using windows. Thanks.

I've got:

import os    
path=r'C:\abc\def\ghi\'    
folderList = os.listdir(path)

Now I need to read all the files in the folder, so I know I need something like

f.open(path)?

Answer

Rushy Panchal picture Rushy Panchal · Apr 14, 2013

You were on the right path:

import os
path = r'C:\abc\def\ghi'  # remove the trailing '\'
data = {}
for dir_entry in os.listdir(path):
    dir_entry_path = os.path.join(path, dir_entry)
    if os.path.isfile(dir_entry_path):
        with open(dir_entry_path, 'r') as my_file:
            data[dir_entry] = my_file.read()