1

I am trying to write a script that goes through a drive. The drive has a folder structure similar to this:

| Folder 1
+--->Folder 1.txt
+--->Folder 1.nfo
| Folder 2
+--->Folder 2.doc
+--->Folder 2.nfo
+--->Folder 2.xls
| Folder 3
+--->Folder 3.txt
+--->Folder 3.nfo

older What I am trying to do is read each of the files in the directory, then when I finish going through the directory, I want to write a log to a text file. I currently open each directory and file using the following:

logfile = open("log.txt")
for path, subdirs, files in os.walk(directory):
  txtfile = 0
  docfile = 0
  xlsfile = 0
  nfofile = 0
  for name in files:
    file = os.path.join(path, name)
    if file.endswith('.txt'):
      txtfile = 1
    elif file.endswith('.doc'):
      docfile = 1
    elif file.endswith('.xls'):
      xlsfile = 1
    elif file.endswith('.nfo'):
      nfofile = 1

    # if all files in a specific directory (Folder 1, Folder 2, etc) have been read, write line to log.txt

I am just not sure how to check the last file. The log will be used to see which files are missing from the directory. Any help on this would be greatly appreciated!

rjbogz
  • 860
  • 1
  • 15
  • 36

2 Answers2

2

You can list all the files in a directory like this: (taken from here)

from os import listdir
from os.path import isfile, join
files = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ]

Then check your file like this:

if file == files[-1]: # do stuff

Or, you can just iterate through files to make it easy, and when it finishes, log your stuff. I recommend doing this.

Community
  • 1
  • 1
jackcogdill
  • 4,900
  • 3
  • 30
  • 48
  • The problem is that I need to write to the log in each directory. I just don't know how to know when it reaches the end of the directory. So, for my example, I need to write to the log after I finish Folder 1, then write again after Folder 2, etc. – rjbogz Dec 18 '12 at 02:52
  • yentup code get you 90% there , just record all files with path within the folder using `files = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ]`, and write down this file list into a log .next time your run the script ,just check files is consistent with log file . – Shawn Zhang Dec 18 '12 at 02:56
0

See if this works:

import os
import os.path as opath


for path, dirs, files in os.walk(directory):
    exts = {}
    for fn, ext in (opath.splitext(f) for f in files):
        exts[ext] = exts.get(ext, 0) + 1

    with open(opath.join(path, "extlog.txt"), "w") as log:
        log.write("\n".join(("%s|%s" % (k, v)) for k, v in exts.items()) + "\n")