Python代码适用于3.61,但不适用于2.7.12
下面我有几行python代码,它在3.61下运行良好,但在2.7.12下运行不好。由于某些原因,file=log\u file可能会抛出错误。我怎么修理它 此外,我认为我的代码不是最佳实践,有什么更好的方法 谢谢大家的帮助Python代码适用于3.61,但不适用于2.7.12,python,file,compatibility,incompatibility,Python,File,Compatibility,Incompatibility,下面我有几行python代码,它在3.61下运行良好,但在2.7.12下运行不好。由于某些原因,file=log\u file可能会抛出错误。我怎么修理它 此外,我认为我的代码不是最佳实践,有什么更好的方法 谢谢大家的帮助 #!/usr/bin/python import os import shutil import time file_location = 'C:\\Users\\pdo\\Desktop\\testing' current_time = time.time() delet
#!/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)
#/usr/bin/python
导入操作系统
进口舒蒂尔
导入时间
文件位置='C:\\Users\\pdo\\Desktop\\testing'
当前时间=time.time()
删除时间=当前时间-86400
tm=time.strftime(“%a,%d%b%Y%H:%M:%S”)
对于os.listdir(文件位置)中的文件:
file\u path=os.path.join(文件位置,文件)
尝试:
#24小时前创建
如果os.stat(文件路径).st\u mtime<删除时间:
如果os.path.isfile(文件路径):
取消链接(文件路径)
打开(文件\u位置+'\\clean\u log.txt,'a')作为日志\u文件:
打印(str(tm)+”-已删除文件:“+文件\路径,文件=日志\文件)
elif os.path.isdir(文件路径):
rmtree(文件路径)
打开(文件\u位置+'\\clean\u log.txt,'a')作为日志\u文件:
打印(str(tm)+”-已删除文件夹:“+文件\路径,文件=日志\文件)
#24小时内创建
elif os.stat(文件路径).st\u mtime>=删除时间:
如果os.path.isfile(文件路径):
打开(文件\u位置+'\\clean\u log.txt,'a')作为日志\u文件:
打印(str(tm)+”-在24小时内创建:“+文件\路径,文件=日志\文件)
elif os.path.isdir(文件路径):
打开(文件\u位置+'\\clean\u log.txt,'a')作为日志\u文件:
打印(str(tm)+”-在24小时内创建:“+文件\路径,文件=日志\文件)
#错误处理
例外情况除外,如e:
打开(文件\u位置+'\\clean\u log.txt,'a')作为日志\u文件:
打印(str(tm)+”-错误:“+e.strerror+”:“+file\u路径,file=log\u文件)
Python3与Python2有显著不同
要使用“file=”(在Py3中引入到print()中),请添加
请注意,在导入所有其他
s
s之前,这一行需要放在文件的顶部。是的,这一行需要放在顶部。现在可以了。非常感谢。
from __future__ import print_function