第2節 python實現檔案讀取

2021-10-05 20:36:24 字數 2485 閱讀 8639

使用read_csv方法讀取,結果為dataframe格式;

在讀取csv檔案時,檔名稱盡量是英文;

引數較多,可以自行控制,但多數時候使用預設引數;

讀取csv時,注意編碼,常用的編碼為utf-8、gbk、gbk2312和gb18030等。

使用to_csv快速儲存。

'''讀取csv檔案'''

import numpy as np

import pandas as pd

import os

os.getcwd(

)# 獲取檔案路徑

os.chdir(

'f:\\dd\\hhh'

)# 檔案所在路徑

#os.chdir(r'f:\dd\hh')

baby=pd.read_csv(

'hhha.csv'

,encoding=

'utf-8'

)# 改變資料型別

#baby=pd.read_csv('hhha.csv',encoding='gbk',dtype=)

bady=pd.read_csv(

'hhha.csv'

,nrows=

100)

# 讀取前100行

baby.info(

)# 檢視資料屬性

# 設定顯示屬性

pd.set_option(

'display.max_columns',20

)pd.set_option(

'display.max_rows'

,100

)# 儲存檔案

bady.to_csv(

'ai.csv'

,encoding=

'utf-8'

,index=

false

)

使用read_excel讀取,讀取結果為dataframe格式;

其它同讀取csv檔案一致,但要考慮工作表sheet頁;

使用to_excel快速儲存為xlsx格式。

df1=pd.read_excel(

'mmm.xlsx'

,encoding=

'utf-8'

,sheet_name=

'name'

)#df1=pd.read_excel('mmm.xlsx',encoding='utf-8',sheet_name=0)

df1.to_excel(

'asdf.xlsx'

,index=flase,sheet_name=

'one'

)

使用sqlalchemy建立連線

通過pandas中read_sql讀取資料;

通過to_sql儲存。

conn=create_engine(

'mysql+pymysql://user:passward@ip:3306/test01'

)

root: 使用者名稱

passward:密碼

ip:伺服器ip,本地電腦用localhost

3306:埠號

test01:資料庫名稱

df.to_sql(name,con=engine,if_exists=

,index=

false

)

name:表名

con:連線;

index=false:不插入索引index

import pandas as pd

import pymysql

from sqlalchemy import create_engine

conn=create_engine(

'mysql+pymysql://root:w123@localhost:3306/test01'

)sql=

'select * from meal'

df1=pd.read_sql(sql,conn )

defquery

(table)

: host=

'localhost'

user=

'root'

password=

'ly11'

database=

'test1'

port=

3306

conn=create_engine(

'mysql+pymysql"//{}:{}@{}:{}/{}'

.format

(user,password,host,port,database)

) sql=

'select * from '

+table

result =pd.read_sql(sql,con=conn)

return result

df2=query(

)

第2節多型

多型概述 同乙個物件,在不同時刻表現出來的不同形態 舉例 貓 我們可以說貓是貓 貓 cat new 貓 我們也可以說貓是動物 動物 animal new 貓 這裡貓在不同的時刻表現出來了不同的形態,這就是多型 多型的前提和體現 package itheima 05 public class anim...

Python開發 第6節 檔案操作

格式 open 檔案路徑 開啟模式 返回值 檔案io物件 開啟模式一共n種 w模式 寫模式write 檔案不存在時會建立檔案,如果檔案已存在則會清空檔案 r模式 讀模式read 檔案不存在就報錯,存在則準備讀取檔案 x模式 抑或模式 檔案存在則報錯,檔案不存在則新建檔案 b模式 二進位制模式 bin...

python實現增量讀取檔案

最近在做乙個小工具,生產者不斷的往乙個txt檔案寫入資料,需要解析增量寫入的資料。實現如下 def read file filename global location location 0 with open filename as fd while true cur location fd.te...