writing lines from multiple text files into one text file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Laura P
    New Member
    • Dec 2011
    • 1

    writing lines from multiple text files into one text file

    I am new to python, and coding in general. Looking at the code below, why is my master file writing the lines from each text file twice?

    Code:
    import os
    import glob
    FileName = "master.txt"
    fout = open(FileName, "w")
    for filename in glob.glob("*txt"):
        fin = open(filename, "r")
        lines = fin.readlines()
        fin.close()
        for lidx in lines:
            fout.write( "%s" % lidx )
    fout.close()


    The combined file I am getting looks like this:
    text from file1
    text from file2
    text from file3
    text from file1
    text from file2
    text from file3

    Any help is appreciated.
    Last edited by bvdet; Dec 12 '11, 03:25 AM. Reason: Add code tags
  • PythonInspired
    New Member
    • Dec 2011
    • 1

    #2
    This code works exactly as you want it to when I test it.

    By chance, do you have any links to these files in the same directory? I know that sounds odd, but when I create links to any of the files I tested this code with, the contents of the linked file were doubled in the output. (the glob section of the python documentation explains this).

    I hope this is of some use, because otherwise your code works perfectly for me.

    Anything more than this and I am absolutely useless. I am a beginner and decided that the best way to improve is to keep looking at code and trying to figure things out as I go.

    Comment

    • bvdet
      Recognized Expert Specialist
      • Oct 2006
      • 2851

      #3
      I don't see anything wrong with your code either. I have a suggestion for improving your code. Instead of
      Code:
          for lidx in lines:
              fout.write( "%s" % lidx )
      I prefer
      Code:
          fout.write("".join(lines))

      Comment

      Working...