简明Python教程之编写一个Pyhton脚本

xiaoxiao2021-02-27  283

三种方案的正确代码:

方案一:

 

#coding=utf-8 import os import time source = ['d:\\testpy1','d:\\testpy2'] target_dir = 'd:\\testpy\\' target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip' zip_command = "zip -qr \"%s\" \"%s\"" % (target,'" "'.join(source)) str = 'sucessful backup to' if os.system(zip_command) == 0: #print str,target#Pycharm正常显示中文 print str.decode('utf-8').encode('gbk'),target#系统控制台正确显示中文 else: print 'Backup Failed'

 

 

 

方案二:

 

 

 

#coding=utf-8 import os import time source = ['d:\\testpy1', 'd:\\testpy2'] target_dir = 'd:\\testpy\\' today = target_dir + time.strftime('%Y%m%d') now = time.strftime('%H%M%S') if not os.path.exists(today): os.mkdir(today) print 'Successfully created directory', today target = today + os.sep + now + '.zip' zip_command = "zip -qr \"%s\" \"%s\"" % (target, '" "'.join(source)) if os.system(zip_command) == 0: print 'Successful backup to', target

 

方案3:

 

#coding=utf-8 import os import time source = ['d:\\testpy1','d:\\testpy2'] target_dir = 'd:\\testpy\\' today = target_dir + time.strftime('%Y%m%d') now = time.strftime('%H%M%S') comment = raw_input('Enter a comment --> ') if len(comment) == 0: target = today + os.sep + now + '.zip' else: target = today + os.sep + now + '_' +\ comment.replace(' ', '_') + '.zip' if not os.path.exists(today):#条件为false时执行下一句 os.mkdir(today) print 'Successfully created directory', today zip_command = "zip -qr \"%s\" \"%s\"" % (target, '" "'.join(source)) if os.system(zip_command) == 0: print 'Successful backup to', target else: print 'Backup FAILED'

 

 

 

 

 

期间遇到字符编码的问题:

情况一:Pycharm控制台输出中文汉字为乱码(即print中要输出字符串的语句) 解决方案:在代码首部加入注释#coding=utf-8 情况二:控制台输出中文乱码 解决方案: str = 'Successful backup to成功' print str.decode('utf-8').encode('gbk')#, target 这里gbk和cp936都可以 遗留问题: Pycharm调用os.system命令时系统提示错误显示为乱码 如zip不是内部或外部命令。 CP936与GBK、GB2312、GB18030区别 http://blog.wuliaoa.com/?p=503 字符编码说明 http://www.cnblogs.com/evening/archive/2012/04/19/2457440.html utf-8转gbk http://www.cnblogs.com/sunshuhai/p/6242275.html

 

转载请注明原文地址: https://www.6miu.com/read-7523.html

最新回复(0)