python - How to open every file in a folder? -
i have python script parse.py, in script open file, file1, , maybe print out total number of characters.
filename = 'file1' f = open(filename, 'r') content = f.read() print filename, len(content)
right now, using stdout direct result output file - output
python parse.py >> output
however, don't want file file manually, there way take care of every single file automatically? like
ls | awk '{print}' | python parse.py >> output
then problem how read file name standardin? or there built-in functions ls , kind of work easily?
thanks!
you can list files in current directory using:
import os filename in os.listdir(os.getcwd()): # stuff
or can list files, depending on file pattern using glob
module:
import glob filename in glob.glob('*.txt'): # stuff
it doesn't have current directory can list them in path want:
path = '/some/path/to/file' filename in os.listdir(path): # stuff filename in glob.glob(os.path.join(path, '*.txt')): # stuff
or can use pipe specified using fileinput
import fileinput line in fileinput.input(): # stuff
and use piping:
ls -1 | python parse.py
Comments
Post a Comment