2017-05-31 70 views
-1

我有幾條python下面,它運行良好3.61但不是2.7.12。它看起來像文件= log_file出於某些原因拋出錯誤。我如何解決它?Python代碼工作在3.61但不是2.7.12

此外,我認爲我的代碼不是最佳實踐,什麼是更好的方法?

謝謝大家的幫助。

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

回答

4

Python3與Python2顯着不同。 Changelist for Python3

要使用「文件=」(它被引入到打印()在PY3),添加

from __future__ import print_function 
+1

注意,這條線需要走在文件的頂部,所有其他'import'前秒。 – jwodder

+0

是的,該行需要在頂部。它現在有效。謝謝。 – Mixer

相關問題