Strange behavior while using glob?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • PythonNewbie
    New Member
    • Nov 2006
    • 18

    Strange behavior while using glob?

    Hello, so I needed to write a quick code that lets me merge whole bunch of text files in a given folder into one text file.

    So, I wrote this up after reading about glob
    [HTML]
    import glob
    #########Enter the directory where your files are located #######

    dirpath ='C:/All_Spot_Spectr a/Spots/*'
    ############### ############### ############### ##########
    w=open('C:/All_Spot_Spectr a/merge.txt','w')
    fileArray=glob. glob(dirpath)
    numFiles=len(fi leArray)
    print numFiles

    for i in range(numFiles) :
    f=open(fileArra y[i],'r')
    line=f.readline ()
    while line!="":
    line=f.readline ()
    print line
    w.write(line)

    w.flush()
    [/HTML]

    Great - it worked just fine. However, when my coworker tried to use it - it did not work. After some debugging, I found out that his directory path had directories which were numbers and that seems to fail with glob. So, for instance, in the original code If I make,

    dirpath ='C:/All_Spot_Spectr a/2007/*'

    it no longer works.

    Funny thing is that this does not happen on my laptop which has Windows XP HE. The problem occurs on the computer that has Windows XP Professional.

    Puzzled.
  • PythonNewbie
    New Member
    • Nov 2006
    • 18

    #2
    Err, my windows version is Windows XP Media Center Edition. It works on that.

    Anyhow, can someone suggest how I can fix this? Maybe, some alternative to glob?

    Comment

    • ghostdog74
      Recognized Expert Contributor
      • Apr 2006
      • 511

      #3
      untested:
      Code:
      import glob,os
      dirpath = os.path.join("C:\\","All_Spot_Spectra","Spots")
      mergetxt = os.path.join("C:\\","All_Spot_Spectra","merge.txt")
      w=open(mergetxt,'a') #if you want to merge, use "a" for append
      os.chdir(dirpath)
      for fi in glob.glob("*.txt"):
              f=open(fi).read()
              w.write(f)
      w.close()

      Comment

      • PythonNewbie
        New Member
        • Nov 2006
        • 18

        #4
        Thank you that works. Now, if I could only figure out how to deal with \

        Comment

        • ghostdog74
          Recognized Expert Contributor
          • Apr 2006
          • 511

          #5
          Originally posted by PythonNewbie
          Thank you that works. Now, if I could only figure out how to deal with \
          where is "\" that you are talking about

          Comment

          • PythonNewbie
            New Member
            • Nov 2006
            • 18

            #6
            I got it figured out. I had started a separate post for it. Someone suggested using raw string when I get input which works like a charm. Thanks a lot - my code is lot cleaner now.

            Comment

            Working...