By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,825 Members | 1,149 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,825 IT Pros & Developers. It's quick & easy.

How to open and read through multiple files in a directory with python

P: 11
I can open and read the content of a single text file using the following line of code.

Expand|Select|Wrap|Line Numbers
  1. f = open('C:\\xyz.text', 'r')
  2.      f.read()
How can I read through multiple files in a directory? as I would like to compare them based on the similarity of their content (textual content). Any suggests? thanks.
Jun 27 '13 #1

✓ answered by bvdet

You can use os.walk to compile a list of file names in a directory. Try the following to see what information os.walk provides:
Expand|Select|Wrap|Line Numbers
  1. for root, dirs, files in os.walk(dir_name):
  2.     print root
  3.     print "  "+"\n  ".join(dirs)
  4.     print "    "+"\n    ".join(files)
  5.     print "*"*40
  6.  

Share this Question
Share on Google+
4 Replies

bvdet
Expert Mod 2.5K+
P: 2,851
You can use os.walk to compile a list of file names in a directory. Try the following to see what information os.walk provides:
Expand|Select|Wrap|Line Numbers
  1. for root, dirs, files in os.walk(dir_name):
  2.     print root
  3.     print "  "+"\n  ".join(dirs)
  4.     print "    "+"\n    ".join(files)
  5.     print "*"*40
  6.  
Jun 27 '13 #2

P: 11
Hi bvdet, thanks for the response. The code worked, but the content of the files were not displayed, only the file names. Is there a way display the contents of the files in the directory? as another module would want to read the content of the files and compare them.
Jun 27 '13 #3

bvdet
Expert Mod 2.5K+
P: 2,851
To open a file from os.walk output, you need to concatenate the root directory and file name:
Expand|Select|Wrap|Line Numbers
  1. f1 = os.path.join(root, file_name)
If you want to see if the contents of two files are equal:
Expand|Select|Wrap|Line Numbers
  1. open(f1).read() == open(f2).read()
Jun 27 '13 #4

P: 11
Hi bvdet, thanks for help. You its now sorted.
Jun 30 '13 #5

Post your reply

Sign in to post your reply or Sign up for a free account.