[Python]有用的小函数集合(不定期更新)

#读csv
def readCsvTo2DList(csvFullFileName,skipHeader,ignoreTail):
    listFile = open(csvFullFileName,'r')
    context  = listFile.read()
    contextList = context.split("\n")

    for i in range(len(contextList)):
        contextList[i]=contextList[i].split(",")
    
    if skipHeader:
        contextList = contextList[1:len(contextList)]
    else:
        contextList = contextList[0:len(contextList)]
    
    if ignoreTail:
        contextList = contextList[0:len(contextList)-1]
    
    return contextList
#获取指定文件夹下特定扩展名的文件列表
def getSpecifiedFile(sourceDir,extension,sort):
    fileList = os.listdir(sourceDir)
    resultFileList = []
    for file in fileList:
        if os.path.splitext(file)[1]==extension:
            resultFileList.append(file)
    if sort:
        resultFileList.sort()
    for i in range(0,len(resultFileList)):
        resultFileList[i] = sourceDir+resultFileList[i]
    return resultFileList
#写csv
def write2DListToCsv(listItem,fileName):
    fileObject = open(fileName, 'w')
    for i in range(len(listItem)):
        for j in range(len(listItem[i])):
            fileObject.write(str(listItem[i][j]))
            if j < len(listItem[i])-1:
                fileObject.write(",")
        if  i < len(listItem)-1: 
            fileObject.write("\n")
    fileObject.close()
#按指定字段对表排序
def sort2DListBySpecifiedField(inputList,index,reverse):
    sortedList = sorted(inputList,key=lambda x:x[index],reverse=reverse)
    return sortedList
#Python2 的中文处理,需要首行指定 # -*- coding: utf-8 -*-
def chineseDecode(inputString):
    return inputString.decode("utf-8").encode("gbk")
#日期转doy
import datetime
def calDOY(strDate):
    doy = int(datetime.datetime.strptime(strDate, '%Y-%m-%d').timetuple().tm_yday)
    return doy
posted @ 2020-07-09 15:01  wsZhang  阅读(242)  评论(0编辑  收藏  举报