使用lua讀取csv檔案

來源:互聯網
上載者:User

新項目準備使用lua開發,待用資料一般都儲存在csv中,所以參考網上很多資料寫了一個讀取csv檔案的小代碼,由於剛剛接觸lua,所以只是實現了功能,以後再最佳化。

引用xv_ly15與笨木頭的功能配置自己項目需求實現

function split(str, reps)    local resultStrsList = {};    string.gsub(str, '[^' .. reps ..']+', function(w) table.insert(resultStrsList, w) end );    return resultStrsList;end--一行一行取用資料local function getRowContent(file)    local content;    local check = false    local count = 0    while true do        local t = file:read()        if not t then            if count == 0 then                check = true            end        break    end    if not content then        content = t    else        content = content..t    end    local i = 1    while true do          local index = string.find(t, "\"", i)          if not index then break end              i = index + 1              count = count + 1          end          if count % 2 == 0 then             check = true             break         end      end      if not check then          assert(1~=1)     end    --返回去掉空格的一行資料,還有方法沒看明白,以後再修改    return content and (string.gsub(content, " ", ""))endfunction loadCsvFile(filePath)    -- 讀取檔案    local alls = {}    local file = io.open(filePath, "r")    while true do    local line = getRowContent(file)    if not line then            break    end    table.insert(alls, line)    end    --[[ 從第2行開始儲存(第一行是標題,後面的行才是內容) 用二維數組儲存:arr[ID][屬性標題字串] ]]    local titles = split(alls[1], ",")    local ID = 1    local arrs = {}    for i = 2, #alls, 1 do        -- 一行中,每一列的內容,第一位為ID        local content = split(alls[i], ",")        ID = tonumber(content[1])        --儲存ID,以便遍曆取用,原來遍曆可以使用in pairs來執行,所以這個不需要了        --table.insert(arrs, i-1, ID)        arrs[ID] = {}        -- 以標題作為索引,儲存每一列的內容,取值的時候這樣取:arrs[1].Title        for j = 1, #titles, 1 do            arrs[ID][titles[j]] = content[j]        end    end    return arrsend


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.