-1

I have few lines of python below and it runs fine under 3.61 but not 2.7.12. It looks like file=log_file throws the error for some reasons. How do I fix it?

Also, I think my codes are not best practice, what is a better approach?

Thank you for your help everyone.

#!/usr/bin/python
import os
import shutil
import time

file_location = 'C:\\Users\\pdo\\Desktop\\testing'
current_time = time.time()
delete_time = current_time - 86400

tm = time.strftime('%a, %d %b %Y %H:%M:%S')

for files in os.listdir(file_location):
    file_path = os.path.join(file_location, files)
    try:

        # Created before 24 hours
        if os.stat(file_path).st_mtime < delete_time:
            if os.path.isfile(file_path):
                os.unlink(file_path)
                with open(file_location + '\\clean_log.txt', 'a') as log_file:
                    print(str(tm) + " - Deleted File: " + file_path, file=log_file)
            elif os.path.isdir(file_path):
                shutil.rmtree(file_path)
                with open(file_location + '\\clean_log.txt', 'a') as log_file:
                    print(str(tm) + " - Deleted Folder: " + file_path, file=log_file)

        # Created within 24 hours
        elif os.stat(file_path).st_mtime >= delete_time:
            if os.path.isfile(file_path):
                with open(file_location + '\\clean_log.txt', 'a') as log_file:
                    print(str(tm) + " - Created within 24 hours: " + file_path, file=log_file)
            elif os.path.isdir(file_path):
                with open(file_location + '\\clean_log.txt', 'a') as log_file:
                    print(str(tm) + " - Created within 24 hours: " + file_path, file=log_file)

    # Error handling
    except Exception as e:
        with open(file_location + '\\clean_log.txt', 'a') as log_file:
            print(str(tm) + " - Error: " + e.strerror + ": " + file_path, file=log_file)
Mixer
  • 183
  • 2
  • 7
  • 15

1 Answers1

4

Python3 is significantly different from Python2. Changelist for Python3

To use "file=" (which was introduced to print() in Py3), add

from __future__ import print_function 
Jerry Zhao
  • 184
  • 11