欢迎来到本课程!

Python 数据导入入门

Hugo Bowne-Anderson

Data Scientist at DataCamp

导入数据

  • 平面文件,如 .txt、.csv
  • 其他软件生成的文件

 

ch_1_1_v2.004.png

Python 数据导入入门

导入数据

  • 平面文件,如 .txt、.csv
  • 其他软件生成的文件
  • 关系型数据库

ch_1_1_v2.005.png

Python 数据导入入门

纯文本文件

纯文本文件示意图 ch_1_1_v2.007.png

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...