Python代码工作在3.61但不是2.7.12

时间:2017-05-31 18:50:11

标签: python file compatibility incompatibility

下面我有几行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)

1 个答案:

答案 0 :(得分:4)

Python3与Python2有很大不同。 Changelist for Python3

使用&#34; file =&#34; (在Py3中引入了print()),添加

from __future__ import print_function