7. Read files (2%)

List files in a directory

from stackoverflow: https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory

os.listdir() will get you everything that's in a directory - files and directories. If you want just files, you could either filter this down using os.path:

from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]

or you could use os.walk() which will yield two lists for each directory it visits - splitting into files and dirs for you. If you only want the top directory you can just break the first time it yields

from os import walk

f = []
for (dirpath, dirnames, filenames) in walk(mypath):
    f.extend(filenames)
    break

Read CSV

讀檔在做什麼事情?讀檔在做的事情就是將一個你知道他是用什麼格式來儲存的資料,讀成Python的物件,這樣就可以用Python來存取裡面的資料。

CSV檔顧名思義為comma seperated value,通常一列就是一筆資料,每一筆資料結尾都有一個\n換行符號,而每一筆資料中的欄位則是用逗號分隔。第一列為欄位名稱(variable names),雖然你看不見,但是每列後面都有一個\n符號,相當於你在鍵盤上敲一個Enter

假設有一個csv檔被讀入EXCEL看起來像是這樣子:

A

B

C

00

01

02

10

11

12

那CSV檔的內容會是下面這樣的格式,整個檔案是一個長長的string,逗號表示分欄、\n表示換行。知道這樣的規則後,當看到如夏的檔案,就會知道這個string是用CSV格式來紀錄的類表格資料。

若我們要在Python或任何程式語言中操作CSV的資料,那就要把該CSV的內容轉為該程式語言的物件。當CSV若被直接讀成標準python的List後會是下面這個「兩層的List」。

例如下面的案例中有三筆資料,但有四列,

Methods to read CSV

當我規劃要讀進一個csv檔時,我可能有三種做法:

  1. 全部靠自己逐行讀,用readlines()來判斷換行符號,將所有資料依照換行符號切割為list內的Element,再將每個Elements遇到逗號進行切割。

  2. 利用csv.reader()函式幫我把文字資料轉換成python物件

  3. 利用pandas的函式讀檔

by hand

by csv_reader

In Pandas way

JSON

Typical json

我們最常見的資料呈現型態是用CSV、Google Sheets或Excel等表述為以下表格型態。我們將用JSON格式來表達這樣的典型資料,藉此看出JSON格式的特性。

site

AQI

PM25

基隆

38

8

新店

40

9

苗栗

76

11

JSON內容的存法很自由,但一般來說,開放資料(表格型態的資料)會表示為List of Dictionary(s)的型態(注意,中括號為List、大括號為Dictionary),例如下方的JSON就是上述表格的JSON表示法。

Read XLS

Last updated