2017-05-31 5 views
-1

J'ai quelques lignes de python ci-dessous et il fonctionne bien sous 3.61 mais pas 2.7.12. Il semble que file = log_file renvoie l'erreur pour certaines raisons. Comment je le répare?Les codes Python fonctionnent dans 3.61 mais pas 2.7.12

En outre, je pense que mes codes ne sont pas de bonnes pratiques, quelle est la meilleure approche?

Nous vous remercions de votre aide à tous.

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

Répondre

4

Python3 est significativement différent de Python2. Changelist for Python3

Pour utiliser « file = » (qui a été introduit à imprimer() dans AP3), ajouter

from __future__ import print_function 
+1

Notez que cette ligne doit aller en haut du fichier, avant tous les autres 'importation, on s. – jwodder

+0

Oui, la ligne doit aller en haut. Ça fonctionne maintenant. Je vous remercie. – Mixer