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

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Tiger1
    New Member
    • Jun 2013
    • 11

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

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

    Code:
    f = open('C:\\xyz.text', 'r')
         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.
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    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:
    Code:
    for root, dirs, files in os.walk(dir_name):
    	print root
    	print "  "+"\n  ".join(dirs)
    	print "    "+"\n    ".join(files)
    	print "*"*40

    Comment

    • Tiger1
      New Member
      • Jun 2013
      • 11

      #3
      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.

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        To open a file from os.walk output, you need to concatenate the root directory and file name:
        Code:
        f1 = os.path.join(root, file_name)
        If you want to see if the contents of two files are equal:
        Code:
        open(f1).read() == open(f2).read()

        Comment

        • Tiger1
          New Member
          • Jun 2013
          • 11

          #5
          Hi bvdet, thanks for help. You its now sorted.

          Comment

          Working...