1. 程式人生 > >多維列表排序、資料夾遍歷、python列表字典csv讀取

多維列表排序、資料夾遍歷、python列表字典csv讀取

  • 多維列表排序:先根據第一列排序,然而第二列,然後第三列
import operator

alist=[[],[],[],[]]
alist.sort(key=operator.itemgetter(0,1,2))
  • 遍歷資料夾下的檔案
import os  
path = "D:/Python34/news" #資料夾目錄  
files= os.listdir(path) #得到資料夾下的所有檔名稱 
for file in files: #遍歷資料夾  
     if not os.path.isdir(file): #判斷是否是資料夾,不是資料夾才打開  
          f = open
(path+"/"+file); #開啟檔案
  • 讀取csv檔案寫入列表
import csv
with open('A.csv','rb') as csvfile:
    reader = csv.reader(csvfile)
    rows= [row for row in reader]
print rows

得到如:
[[‘No.’, ‘Name’, ‘Age’, ‘Score’],
[‘1’, ‘Apple’, ‘12’, ‘98’],
[‘2’, ‘Ben’, ‘13’, ‘97’],
[‘3’, ‘Celia’, ‘14’, ‘96’],
[‘4’, ‘Dave’, ‘15’, ‘95’]]

  • python列表、字典與csv

1、將一個二重列表[[],[]]寫入到csv檔案中
2、從文字檔案中讀取返回為列表
3、將一字典寫入到csv檔案中
4、從csv檔案中讀取一個字典
5、從csv檔案中讀取一個計數字典

# 功能:將一個二重列表寫入到csv檔案中
# 輸入:檔名稱,資料列表
def createListCSV(fileName="", dataList=[]):
    with open(fileName, "wb") as csvFile:
        csvWriter = csv.writer(csvFile)
        for data in
dataList: csvWriter.writerow(data) csvFile.close
# 功能:從文字檔案中讀取返回為列表的形式
# 輸入:檔名稱,分隔符(預設,)
def readListCSV(fileName="", splitsymbol=","):
    dataList = []
    with open(fileName, "r") as csvFile:
        dataLine = csvFile.readline().strip("\n")
        while dataLine != "":
            tmpList = dataLine.split(splitsymbol)
            dataList.append(tmpList)
            dataLine = csvFile.readline().strip("\n")
        csvFile.close()
    return dataList
# 功能:將一字典寫入到csv檔案中
# 輸入:檔名稱,資料字典
def createDictCSV(fileName="", dataDict={}):
    with open(fileName, "wb") as csvFile:
        csvWriter = csv.writer(csvFile)
        for k,v in dataDict.iteritems():
            csvWriter.writerow([k,v])
        csvFile.close()
# 功能:從csv檔案中讀取一個字典
# 輸入:檔名稱,keyIndex,valueIndex
def readDictCSV(fileName="", keyIndex=0, valueIndex=1):
    dataDict = {}
    with open(fileName, "r") as csvFile:
        dataLine = csvFile.readline().strip("\n")
        while dataLine != "":
            tmpList = dataLine.split(splitsymbol)
            dataDict[tmpList[keyIndex]] = tmpList[valueIndex]
            dataLine = csvFile.readline().strip("\n")
        csvFile.close()
    return dataDict
# 功能:從csv檔案中讀取一個計數字典
# 輸入:檔名稱,keyIndex
def readDictCSV(fileName="", keyIndex=0):
    dataDict = {}
    with open(fileName, "r") as csvFile:
        dataLine = csvFile.readline().strip("\n")
        while dataLine != "":
            tmpList = dataLine.split(splitsymbol)
            if dataDict.get(tmpList[keyIndex]) == None:
                dataDict[tmpList[keyIndex]] = 0
            dataDict[tmpList[keyIndex]] = dataDict.get(tmpList[keyIndex]) + 1
            dataLine = csvFile.readline().strip("\n")
        csvFile.close()
    return dataDict