How to open every file in a folder How to open every file in a folder python python

How to open every file in a folder


Os

You can list all files in the current directory using os.listdir:

import osfor filename in os.listdir(os.getcwd()):   with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode      # do your stuff

Glob

Or you can list only some files, depending on the file pattern using the glob module:

import globfor filename in glob.glob('*.txt'):   with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode      # do your stuff

It doesn't have to be the current directory you can list them in any path you want:

path = '/some/path/to/file'for filename in glob.glob(os.path.join(path, '*.txt')):   with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode      # do your stuff

PipeOr you can even use the pipe as you specified using fileinput

import fileinputfor line in fileinput.input():    # do your stuff

And you can then use it with piping:

ls -1 | python parse.py


You should try using os.walk.

import osyourpath = 'path'for root, dirs, files in os.walk(yourpath, topdown=False):    for name in files:        print(os.path.join(root, name))        stuff    for name in dirs:        print(os.path.join(root, name))        stuff


I was looking for this answer:

import os,globfolder_path = '/some/path/to/file'for filename in glob.glob(os.path.join(folder_path, '*.htm')):  with open(filename, 'r') as f:    text = f.read()    print (filename)    print (len(text))

you can choose as well '*.txt' or other ends of your filename