天天看點

python文本檔案讀取與存儲

# CSV檔案的讀取

In [1]:

import csv      # 通過Python自帶的csv庫建立CSV檔案
fp = open('H:/python資料分析/資料/ch4ex1.csv','w',newline='')    # 建立CSV檔案
writer = csv.writer(fp)    
writer.writerow(('id','name','grade'))    # 向CSV寫入資料
writer.writerow(('1','lucky','87'))
writer.writerow(('2','peter','92'))
writer.writerow(('3','lili','85'))
fp.close()
           

In [2]:

!type H:\python資料分析\資料\ch4ex1.csv   
'''通過!type方法檢視資料,type方法隻适用于Windows系統,UNIX系統使用!cat指令。'''
           
id,name,grade
1,lucky,87
2,peter,92
3,lili,85
           

In [3]:

import pandas as pd
df = pd.read_csv(open('H:/python資料分析/資料/ch4ex1.csv'))    # 使用read_csv函數讀取CSV檔案
'''讀取CSV檔案時,如果檔案路徑中有中文,需要加open函數,否則會報錯'''
df
           

Out[3]:

id name grade
1 lucky 87
1 2 peter 92
2 3 lili 85

In [4]:

df = pd.read_table(open('H:/python資料分析/資料/ch4ex1.csv'),sep=',')
'''使用read_table進行讀取CSV檔案,指定分隔符即可'''
df
           

Out[4]:

id name grade
1 lucky 87
1 2 peter 92
2 3 lili 85

In [5]:

df = pd.read_csv(open('H:/python資料分析/資料/ch4ex1.csv'),index_col='id')
'''預設情況下,讀取的DataFrame的行索引是從0開始進行計數'''
'''通過index_col參數指定id列為行索引'''
df
           

Out[5]:

name grade
id
1 lucky 87
2 peter 92
3 lili 85

In [6]:

import csv      # 通過Python自帶的csv庫建立CSV檔案
fp = open('H:/python資料分析/資料/ch4ex2.csv','w',newline='')
writer = csv.writer(fp)
writer.writerow(('school','id','name','grade'))    # 寫入資料
writer.writerow(('a','1','lucky','87'))
writer.writerow(('a','2','peter','92'))
writer.writerow(('a','3','lili','85'))
writer.writerow(('b','1','coco','78'))
writer.writerow(('b','2','kevin','87'))
writer.writerow(('b','3','heven','96'))
fp.close()
           

In [7]:

!type H:\python資料分析\資料\ch4ex2.csv    # 檢視資料
           
school,id,name,grade
a,1,lucky,87
a,2,peter,92
a,3,lili,85
b,1,coco,78
b,2,kevin,87
b,3,heven,96
           

In [8]:

df = pd.read_csv(open('H:/python資料分析/資料/ch4ex2.csv'),index_col=[0,'id'])  
'''階層化索引,傳入列編号或者列名組成的清單即可'''
df
           

Out[8]:

name grade
school id
a 1 lucky 87
2 peter 92
3 lili 85
b 1 coco 78
2 kevin 87
3 heven 96

In [9]:

import csv    # 通過Python自帶的csv庫建立CSV檔案
fp = open('H:/python資料分析/資料/ch4ex3.csv','w',newline='')
writer = csv.writer(fp)
writer.writerow(('1','lucky','87'))
writer.writerow(('2','peter','92'))
writer.writerow(('3','lili','85'))
fp.close()
           

In [10]:

!type H:\python資料分析\資料\ch4ex3.csv    # 檢視資料
           
1,lucky,87
2,peter,92
3,lili,85
           

In [12]:

df = pd.read_csv(open('H:/python資料分析/資料/ch4ex3.csv'))    # 預設情況讀取,會指定第一行為标題行
df
           

Out[12]:

1 lucky 87
2 peter 92
1 3 lili 85

In [13]:

df = pd.read_csv(open('H:/python資料分析/資料/ch4ex3.csv'),header=None)   # 通過header參數配置設定預設的标題行
'''
如果表頭的type和csv内容的type相一緻的時候,那麼直接讀取,會讓第一行來當表頭
此時加header=None,可以讓第一行不當表頭,而預設給0、1 來當表頭
header這個屬性是指,在不加header=None這個屬性所出來的資料的基礎上,把那個資料的表頭去掉,換成0開頭的表頭
'''
df
           

Out[13]:

1 2
1 lucky 87
1 2 peter 92
2 3 lili 85

In [14]:

df = pd.read_csv(open('H:/python資料分析/資料/ch4ex3.csv'),names=['id','name','grade'])
'''
通過names參數給其指定列名
當設定了names屬性之後,header無論設不設定,都會是None
'''
df
           

Out[14]:

id name grade
1 lucky 87
1 2 peter 92
2 3 lili 85

In [15]:

import csv    # 通過Python自帶的csv庫建立CSV檔案并寫入資料
fp = open('H:/python資料分析/資料/ch4ex4.csv','w',newline='')
writer = csv.writer(fp)
writer.writerow(['#This is grade'])
writer.writerow(('id','name','grade'))
writer.writerow(('1','lucky','87'))
writer.writerow(('2','peter','92'))
writer.writerow(('3','lili','85'))
writer.writerow(['#time'])
fp.close()
           

In [16]:

!type H:\python資料分析\資料\ch4ex4.csv   # 檢視資料
           
#This is grade
id,name,grade
1,lucky,87
2,peter,92
3,lili,85
#time
           

In [17]:

df = pd.read_csv(open('H:/python資料分析/資料/ch4ex4.csv'),skiprows=[0,5])   # 通過skiprows參數跳過一些行
'''無論是帶表頭還是不帶表頭,skiprows=2的效果,都是讀第三行(也就是跳了兩行讀)'''
df
           

Out[17]:

id name grade
1 lucky 87
1 2 peter 92
2 3 lili 85

In [19]:

df = pd.read_csv(open('H:/python資料分析/資料/titanic.csv'),nrows=10)
'''通過nrows參數,可以選擇隻讀取部分行資料'''
df
           

Out[19]:

PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
1 3 Braund, Mr. Owen Harris male 22.0 1 A/5 21171 7.2500 NaN S
1 2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38.0 1 PC 17599 71.2833 C85 C
2 3 1 3 Heikkinen, Miss. Laina female 26.0 STON/O2. 3101282 7.9250 NaN S
3 4 1 1 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1 113803 53.1000 C123 S
4 5 3 Allen, Mr. William Henry male 35.0 373450 8.0500 NaN S
5 6 3 Moran, Mr. James male NaN 330877 8.4583 NaN Q
6 7 1 McCarthy, Mr. Timothy J male 54.0 17463 51.8625 E46 S
7 8 3 Palsson, Master. Gosta Leonard male 2.0 3 1 349909 21.0750 NaN S
8 9 1 3 Johnson, Mrs. Oscar W (Elisabeth Vilhelmina Berg) female 27.0 2 347742 11.1333 NaN S
9 10 1 2 Nasser, Mrs. Nicholas (Adele Achem) female 14.0 1 237736 30.0708 NaN C

In [20]:

df = pd.read_csv(open('H:/python資料分析/資料/titanic.csv'),nrows=10,usecols=['Survived','Sex'])
'''通過usecols參數進行部分列的選取'''
df
           

Out[20]:

Survived Sex
male
1 1 female
2 1 female
3 1 female
4 male
5 male
6 male
7 male
8 1 female
9 1 female

In [21]:

df = pd.read_csv(open('H:/python資料分析/資料/titanic.csv'))
'''
在處理很大檔案的時候,需要對檔案進行逐塊讀取,
首先通過info函數檢視泰坦尼克号的生還者資料,共有891條資料
'''
df.info()
           
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 891 entries, 0 to 890
Data columns (total 12 columns):
PassengerId    891 non-null int64
Survived       891 non-null int64
Pclass         891 non-null int64
Name           891 non-null object
Sex            891 non-null object
Age            714 non-null float64
SibSp          891 non-null int64
Parch          891 non-null int64
Ticket         891 non-null object
Fare           891 non-null float64
Cabin          204 non-null object
Embarked       889 non-null object
dtypes: float64(2), int64(5), object(5)
memory usage: 83.6+ KB
           

In [22]:

chunker = pd.read_csv(open('H:/python資料分析/資料/titanic.csv'),chunksize=100)
'''通過chunksize參數,即可逐漸讀取檔案
設定讀取的行數,傳回一個固定行數的疊代器,
每次讀取隻消耗相應行數對應的dataframe的記憶體,
進而可以有效的解決記憶體消耗過多的問題
'''
chunker
           

Out[22]:

<pandas.io.parsers.TextFileReader at 0x96c3cf8>           

In [23]:

df = pd.read_csv(open('H:/python資料分析/資料/titanic.csv'))
df['Sex'].value_counts()
           

Out[23]:

male      577
female    314
Name: Sex, dtype: int64           

In [24]:

from pandas import Series
import pandas as pd
chunker = pd.read_csv(open('H:/python資料分析/資料/titanic.csv'),chunksize=100)
sex = Series([])
for i in chunker:       # 傳回的是可疊代的TextFileReader。通過疊代,可以對Sex列進行計數
    sex = sex.add(i['Sex'].value_counts(),fill_value=0)
sex
           

Out[24]:

male      577.0
female    314.0
dtype: float64           

read_csv/read_table參數

python文本檔案讀取與存儲

TXT檔案的讀取

In [25]:

fp = open('H:/python資料分析/資料/ch4ex6.txt','a+')   # 建立TXT檔案
fp.writelines('id?name?grade'+'\n')    # 寫入資料
fp.writelines('1?lucky?87'+'\n')
fp.writelines('2?peter?92'+'\n')
fp.writelines('3?lili?85'+'\n')
fp.close()
           

In [26]:

!type H:\python資料分析\資料\ch4ex6.txt   # 檢視資料
           
id?name?grade
1?lucky?87
2?peter?92
3?lili?85
           

In [27]:

import pandas as pd
df = pd.read_table(open('H:/python資料分析/資料/ch4ex6.txt'),sep='?')   # 讀取TXT檔案
'''通過read_table函數中的sep參數進行分隔符的指定'''
df
           

Out[27]:

id name grade
1 lucky 87
1 2 peter 92
2 3 lili 85

In [28]:

!type H:\python資料分析\資料\ch4ex7.txt  # 檢視TXT檔案,以空格隔開的檔案
           
id   name grade
1 lucky  87
2  peter    92
3  lili 85
           

In [29]:

df = pd.read_table(open('H:/python資料分析/資料/ch4ex7.txt'),sep='\s+')  # 正規表達式處理空格讀取資料
df
           

Out[29]:

id name grade
1 lucky 87
1 2 peter 92
2 3 lili 85

#文本存儲

In [30]:

import pandas as pd
df = pd.read_csv(open('H:/python資料分析/資料/ch4ex1.csv'))
df
           

Out[30]:

id name grade
1 lucky 87
1 2 peter 92
2 3 lili 85

In [31]:

'''利用DataFrame的to_csv方法,可以将資料存儲到以逗号分隔的CSV檔案中'''
df.to_csv('H:/python資料分析/資料/out1.csv')
!type H:\python資料分析\資料\out1.csv
           
,id,name,grade
0,1,lucky,87
1,2,peter,92
2,3,lili,85
           

In [32]:

'''通過sep參數指定存儲的分隔符,預設情況下會存儲行和列索引'''
df.to_csv('H:/python資料分析/資料/out2.csv',sep='?')
!type H:\python資料分析\資料\out2.csv
           
?id?name?grade
0?1?lucky?87
1?2?peter?92
2?3?lili?85
           

In [33]:

'''通過設定index和header分别處理行和列索引'''
df.to_csv('H:/python資料分析/資料/out3.csv',index=False)
!type H:\python資料分析\資料\out3.csv
           
id,name,grade
1,lucky,87
2,peter,92
3,lili,85