2017-05-31 22 views
-1

私は以下の行のPythonを数行しか持っていませんが、3.61では2.7.12ではなく正常に動作します。何らかの理由でfile = 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

は、他のすべての `import`前に、この行は、ファイルの先頭に行く必要があると

from __future__ import print_function 
+1

注意を追加し、(()PY3で印刷するために導入された)「=ファイル」を使用するにはs。 – jwodder

+0

はい、行は先頭に移動する必要があります。それは今働く。ありがとうございました。 – Mixer

関連する問題