歡迎加入本課程!

Python 資料匯入入門

Hugo Bowne-Anderson

Data Scientist at DataCamp

匯入資料

  • 扁平檔案,如 .txt、.csv
  • 其他軟體的檔案

 

第 1 章圖 1.004

Python 資料匯入入門

匯入資料

  • 扁平檔案,如 .txt、.csv
  • 其他軟體的檔案
  • 關聯式資料庫

第 1 章圖 1.005

Python 資料匯入入門

純文字檔

第 1 章圖 1.007

Python 資料匯入入門

表格資料

titanic.csv

                        Name      Sex  Cabin  Survived
     Braund, Mr. Owen Harris     male    NaN         0
  Cumings, Mrs. John Bradley   female    C85         1
      Heikkinen, Miss. Laina   female    NaN         1
Futrelle, Mrs. Jacques Heath   female   C123         1
    Allen, Mr. William Henry     male    NaN         0
1 來源:Kaggle
Python 資料匯入入門

表格資料

titanic.csv

titanic.csv(已反白一列)

Python 資料匯入入門

表格資料

titanic.csv

titanic.csv(已反白一欄)

  • 扁平檔案
Python 資料匯入入門

讀取文字檔

filename = 'huck_finn.txt'

file = open(filename, mode='r') # 'r' is to read
text = file.read()
file.close()
Python 資料匯入入門

印出文字檔

print(text)
YOU don't know about me without you have read a book by
the name of The Adventures of Tom Sawyer; but that 
ain't no matter. That book was made by Mr. Mark Twain,
and he told the truth, mainly. There was things which 
he stretched, but mainly he told the truth.  That is 
nothing. never seen anybody but lied one time or 
another, without it was Aunt Polly, or the widow, or 
maybe Mary. Aunt Polly--Tom's Aunt Polly, she is--and
Mary, and the Widow Douglas is all told about in that
book, which is mostly a true book, with some 
stretchers, as I said before.
Python 資料匯入入門

寫入檔案

filename = 'huck_finn.txt'
file = open(filename, mode='w')  # 'w' is to write
file.close()
Python 資料匯入入門

with 內容管理器

with open('huck_finn.txt', 'r') as file:
    print(file.read())
YOU don't know about me without you have read a book by
the name of The Adventures of Tom Sawyer; but that 
ain't no matter. That book was made by Mr. Mark Twain,
and he told the truth, mainly. There was things which 
he stretched, but mainly he told the truth.  That is 
nothing. never seen anybody but lied one time or 
another, without it was Aunt Polly, or the widow, or 
maybe Mary. Aunt Polly--Tom's Aunt Polly, she is--and 
Mary, and the Widow Douglas is all told about in that 
book, which is mostly a true book, with some 
stretchers, as I said before.
Python 資料匯入入門

在練習中,你將:

  • 在主控台印出檔案
  • 印出特定行數
  • 討論扁平檔
Python 資料匯入入門

一起來練習吧!

Python 資料匯入入門

Preparing Video For Download...