Python 代码在 3.61 中有效,但在 2.7.12 中无效

Python codes work in 3.61 but not 2.7.12

我下面有几行 python,它在 3.61 下运行良好,但在 2.7.12 下运行不正常。看起来 file=log_file 由于某些原因抛出错误。我该如何解决?

此外,我认为我的代码不是最佳实践,什么是更好的方法?

谢谢大家的帮助。

#!/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)

Python3 与 Python2 明显不同。 Changelist for Python3

要使用 "file="(在 Py3 中引入到 print()),添加

from __future__ import print_function