472,964 Members | 2,428 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,964 software developers and data experts.

File log

I am trying to make a script to check files in a folder, then see later if the files have been changed at all..

I have this working to make the original file (data log with files,file_sizes, and dates).

Expand|Select|Wrap|Line Numbers
  1. log_file = open('log_file.txt', 'w')
  3. for root,dirs,files in os.walk(cwd):   
  4.    for folder in glob.glob(root):
  5.       for file in glob.glob(folder + '/*.**'):
  6.          file_path = os.path.split(file)[1]
  7.          size = os.stat(file)
  8.          file_date = time.strftime("%m/%d/%y %H:%M:%S", time.localtime())
  9.          data = '%s | %s bytes | %s ' % (os.path.split(file_path)[1], size.st_size, file_date)
  10.          log_file.write(data+'\n')
  12. log_file.close()
But when I try to use this snippet in a function in a bigger script it gives me this error...

Expand|Select|Wrap|Line Numbers
  1. Traceback (most recent call last):
  2.   File "C:\Documents and Settings\Scripts\testing_grounds\Log_file\log_file.py", line 27, in <module>
  3.     log_file2.write(data+'\n')
  4. NameError: name 'data' is not defined
script I am trying to get to work...

Expand|Select|Wrap|Line Numbers
  1. #!/usr/python/bin
  2. # Filename: log_file.py
  4. """
  5. This file takes a file in a directory and writes a log file containing all the filenames, modification times and filesizes. Then on a later date, the program will check this log file to detect any changes in the directory
  6. """
  8. import os, glob, time, filecmp, tempfile
  10. cwd = os.getcwd()
  12. def datalog():
  14.    for root,dirs,files in os.walk(cwd):   
  15.       for folder in glob.glob(root):
  16.          for file in glob.glob(folder + '/*.**'):
  17.             file_path = os.path.split(file)[1]
  18.             size = os.stat(file)
  19.             file_date = time.strftime("%m/%d/%y %H:%M:%S", time.localtime())
  20.             data = '%s | %s bytes | %s ' % (os.path.split(file_path)[1], size.st_size, file_date)
  22. if os.path.exists('log_file.txt'):
  24.    # Create a 'temporary' file to store current directory's dimensions
  25.    log_file2 = open('log_file2.txt', 'w')
  26.    datalog()
  27.    log_file2.write(data+'\n')
  28.    log_file2.close()
  30.    # Compair the directory's current dimensions to previous modifications
  31.    if filecmp.cmp('log_file.txt', 'log_file2.txt'):
  32.       print 'No files have been modified'
  33.       os.remove('log_file2.txt')
  35.    else:
  36.       print 'The directory has been modified'
  37.       done = raw_input("When done compariing the logs type 'done' ")
  38.       if done == done:
  39.          os.remove('log_file.txt')
  40.          os.remove('log_file2.txt')
  41.          log_file = open('log_file.txt', 'w')
  42.          datalog()
  43.          log_file.write(data+'\n')
  44.          log_file.close()
  46. else:
  48.    log_file = open('log_file.txt', 'w')
  49.    log_file = open('log_file.txt', 'w')
  50.    log_file.write(data+'\n')
  51.    log_file.close()
Nov 24 '08 #1
3 2255
2,851 Expert Mod 2GB
Variable data is local to datalog().The script will never see data unless you return it to a module global variable, or move the code causing the error into the function.
Nov 24 '08 #2
The point was though I didn't want to have to type that code 4 times and make the script really long. (I would need it typed every time I typed datalog()) Is there a way to shorten the code by not needing to type ...

Expand|Select|Wrap|Line Numbers
  1. for root,dirs,files in os.walk(cwd):   
  2.    for folder in glob.glob(root):
  3.       for file in glob.glob(folder + '/*.**'):
  4.          file_path = os.path.split(file)[1]
  5.          size = os.stat(file)
  6.          file_date = time.strftime("%m/%d/%y %H:%M:%S", time.localtime())
  7.          data = '%s | %s bytes | %s ' % (os.path.split(file_path)[1], size.st_size, file_date)
4 times?
Nov 24 '08 #3
2,851 Expert Mod 2GB
Try modifying your code to return a list of file data, and write the joined list to file. This is untested.
Expand|Select|Wrap|Line Numbers
  1. def datalog():
  2.     dataList = []
  3.     for root,dirs,files in os.walk(cwd):   
  4.         for folder in glob.glob(root):
  5.             for file in glob.glob(folder + '/*.**'):
  6.                 file_path = os.path.split(file)[1]
  7.                 size = os.stat(file)
  8.                 file_date = time.strftime("%m/%d/%y %H:%M:%S", time.localtime())
  9.                 dataList.append('%s | %s bytes | %s ' % (os.path.split(file_path)[1], size.st_size, file_date))
  10.     return dataList
  12. if os.path.exists('log_file.txt'):
  13.     # Create a 'temporary' file to store current directory's dimensions
  14.     log_file2 = open('log_file2.txt', 'w')
  15.     log_file2.write('\n'.join(datalog()))
  16.     log_file2.close()
If you want the date each file was last modified, you need to do this:
Expand|Select|Wrap|Line Numbers
  1. file_date = time.strftime("%m/%d/%Y %H:%M:%S", time.localtime(os.path.getmtime(fn)))
Nov 24 '08 #4

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

Similar topics

by: matt | last post by:
I have compiled some code, some written by me, some compiled from various sources online, and basically i've got a very simple flat file photo gallery. An upload form, to upload the photos and give...
by: Dave Smithz | last post by:
Hi There, I have a PHP script that sends an email with attachment and works great when provided the path to the file to send. However this file needs to be on the same server as the script. ...
by: Joseph | last post by:
Hi, I'm having bit of questions on recursive pointer. I have following code that supports upto 8K files but when i do a file like 12K i get a segment fault. I Know it is in this line of code. ...
by: StGo | last post by:
How can i read/write file's custom attributs(like subject,author...) in C#??? Thanks :))
by: Lokkju | last post by:
I am pretty much lost here - I am trying to create a managed c++ wrapper for this dll, so that I can use it from c#/vb.net, however, it does not conform to any standard style of coding I have seen....
by: Sky Sigal | last post by:
I have created an IHttpHandler that waits for uploads as attachments for a webmail interface, and saves it to a directory that is defined in config.xml. My question is the following: assuming...
by: Roy | last post by:
Hi, I have a problem that I have been working with for a while. I need to be able from server side (asp.net) to detect that the file i'm streaming down to the client is saved...
by: Shapper | last post by:
Hello, I created a script to upload a file. To determine the file type I am using userPostedFile.ContentType. For example, for a png image I get "image/png". My questions are: 1. Where can...
by: troutbum | last post by:
I am experiencing problems when one user has a document open through a share pointing to the web site. I use the dsolefile to read the contents of a particular directory and then display them in a...
by: thjwong | last post by:
I'm using WinXP with Microsoft Visual C++ .NET 69462-006-3405781-18776, Microsoft Development Environment 2003 Version 7.1.3088, Microsoft .NET Framework 1.1 Version 1.1.4322 SP1 Most developers...
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
by: Aliciasmith | last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 1 Nov 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM) Please note that the UK and Europe revert to winter time on...
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.