File log
我正在尝试编写一个脚本来检查文件夹中的文件,然后在以后查看这些文件是否已更改。
我用这个来制作原始文件(包含文件、文件大小和日期的数据记录)。
选择 | 换行 | 行号
- log_file = open('log_file.txt', 'w')
- for root,dirs,files in os.walk(cwd):
- for folder in glob.glob(root):
- for file in glob.glob(folder + '/*.**'):
- file_path = os.path.split(file)[1]
- size = os.stat(file)
- file_date = time.strftime("%m/%d/%y %H:%M:%S", time.localtime())
- data = '%s | %s bytes | %s ' % (os.path.split(file_path)[1], size.st_size, file_date)
- log_file.write(data+'\n')
- log_file.close()
但是,当我试图在一个更大的脚本的函数中使用这个代码片段时,它给出了这个错误...
选择 | 换行 | 行号
- Traceback (most recent call last):
- File "C:\Documents and Settings\Scripts\testing_grounds\Log_file\log_file.py", line 27, in <module>
- log_file2.write(data+'\n')
- NameError: name 'data' is not defined
我正试着开始工作的剧本...
选择 | 换行 | 行号
- #!/usr/python/bin
- # Filename: log_file.py
- """
- 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
- """
- import os, glob, time, filecmp, tempfile
- cwd = os.getcwd()
- def datalog():
- for root,dirs,files in os.walk(cwd):
- for folder in glob.glob(root):
- for file in glob.glob(folder + '/*.**'):
- file_path = os.path.split(file)[1]
- size = os.stat(file)
- file_date = time.strftime("%m/%d/%y %H:%M:%S", time.localtime())
- data = '%s | %s bytes | %s ' % (os.path.split(file_path)[1], size.st_size, file_date)
- if os.path.exists('log_file.txt'):
- # Create a 'temporary' file to store current directory's dimensions
- log_file2 = open('log_file2.txt', 'w')
- datalog()
- log_file2.write(data+'\n')
- log_file2.close()
- # Compair the directory's current dimensions to previous modifications
- if filecmp.cmp('log_file.txt', 'log_file2.txt'):
- print 'No files have been modified'
- os.remove('log_file2.txt')
- else:
- print 'The directory has been modified'
- done = raw_input("When done compariing the logs type 'done' ")
- if done == done:
- os.remove('log_file.txt')
- os.remove('log_file2.txt')
- log_file = open('log_file.txt', 'w')
- datalog()
- log_file.write(data+'\n')
- log_file.close()
- else:
- log_file = open('log_file.txt', 'w')
- log_file = open('log_file.txt', 'w')
- log_file.write(data+'\n')
- log_file.close()