[Python] Note Book
1. 字符串数字左边自动补零
"2".zfill(3) => "002"
"123".zfill(4) => "0123"
"12".zfill(1) => "12" #(大于定义的width则保持原来的长度)
2. Mac OSX中拖入文件路径到终端末尾多空格和文件夹名称多空格,解决方法
例:/Users/it-0003005/Desktop/Python\ Test\ Folder 1口
strPath = raw_input("strPath: ") #等待输入路径 strPath = (''.join(strPath.split('\\')))[0:-1] print strPath
3. 遍历需要的文件
def recursivelyFindFilesAtPath(dirPath, partInfoName): fileList = [] filesPath = glob.glob(os.path.join(dirPath, '*')) #print "fiesPath = %s" %filesPath for filePath in filesPath: #print "filePath = %s" %filePath if os.path.isfile(filePath) and fnmatch.fnmatch(filePath, partInfoName): fileList.append(filePath) elif os.path.isdir(filePath): fileList += recursivelyFindFilesAtPath(filePath, partInfoName) return fileList fileListWithFixtureLogs = recursivelyFindFilesAtPath("/Users/xxx/Desktop/", "*fixtureSlot*.log")
4. 多行匹配
if os.path.isfile(oneSIPFilePathWithAttributesCSV): print "-> Attributes.csv exist" try: with open(oneSIPFilePathWithAttributesCSV, "r") as f: content = f.read() #读取文件中所有内容,为一个字符串 regex = re.compile("(FN.+?)$", re.M) if regex.search(content) != None: print "xyz ===> "+regex.search(content).group(1) sn = regex.search(content).group(1) print "SN = " + sn regexSlot = re.compile("fixtureSlot([0-9]{1}).log$", re.M) print "Slot ===> "+regexSlot.search(oneSIPFilePathWithFixtureLog).group(1) slot = regexSlot.search(oneSIPFilePathWithFixtureLog).group(1) snList[trayID+'_'+slot] = sn print snList else: print "xyz ===> Can't find keyword from content!" #m = re.search(r'SrNm: (.*)$', content) #print "DIAGSVER = "+ m.group(0) # except Exception,e: # print Exception,":",e except: print "GET SN FAIL!" else: print "No attr log existed"
5. 字典按key值正排序
snListSorted = sorted(snList.iteritems(), key = lambda snList:snList[0], reverse = False)
6. 终端输出添加背景色
def colorPrint(colorDisplayMode, foreGroundCorlor, groundColor, displayString): """[设置输出字体的颜色和背景色(显示在终端上)] [description] Arguments: colorDisplayMode {[Int]} -- [显示方式] foreGroundCorlor {[Int]} -- [前景色] groundColor {[Int]} -- [背景色] displayString {[str]} -- [需要显示的内容] 显示方式: 0(默认值)、1(高亮)、22(非粗体)、4(下划线)、24(非下划线)、 5(闪烁)、25(非闪烁)、7(反显)、27(非反显) 前景色: 30(黑色)、31(红色)、32(绿色)、 33(黄色)、34(蓝色)、35(洋 红)、36(青色)、37(白色) 背景色: 40(黑色)、41(红色)、42(绿色)、 43(黄色)、44(蓝色)、45(洋 红)、46(青色)、47(白色) """ #开头部分:\033[显示方式;前景色;背景色m + 结尾部分:\033[0m colorBegin = "\033[%d;%d;%dm" %(colorDisplayMode, foreGroundCorlor, groundColor) colorEnd = "\033[0m" print colorBegin+displayString+colorEnd
无耻
不负自己