April 6th, 2005, 02:01 PM
Read Multiple text File From a Directory Usin Python
I have 100 text file
1. I need to Read all the Text File using a for loop
so that i can display the content of all the file one after
2. I also want to read text file based on pattern of the filename prefix
i have files like
1. QUESTION IS TO READ ALL THE TEXT FILE
2. READ ONLY TEXT FILE WITH PREFIX : DEMO
pLEASE HELP ME WITH THIS.
April 6th, 2005, 02:29 PM
glob is your friend
# all files
for fil in glob.glob('*'):
# do something with the files
# DEMO files only
for fil in glob.glob('DEMO*'):
# do blabla
Comments on this post
April 6th, 2005, 03:41 PM
You could also use the os modules listdir() function however you will need to check the prefix manually, you can do this using the startswith() string method.
In both cases you should check that the item is a file unless you can be sure that no sub directories will ever be present since this will crash your program.
In this example you can see the use of the os.path.isfile() function to check if the item is a file or not. You can also see the use of the os.path.join() function, which is used to join the path and the itemName in a way that is cross platform.
path = ''
for itemName in os.listdir(path):
#Loops over each itemName in the path. Joins the path and the itemName
#and assigns the value to itemName.
itemName = os.path.join(path, itemName)
print file(itemName, 'r').read()
Hope this helps,
April 6th, 2005, 04:08 PM
Originally Posted by netytan