專門做男裝的網(wǎng)站設(shè)計(jì)網(wǎng)站排行
一、C++版
程序運(yùn)行時(shí)產(chǎn)生的數(shù)據(jù)都屬于臨時(shí)數(shù)據(jù),程序—旦運(yùn)行結(jié)束都會(huì)被釋放通過文件可以將數(shù)據(jù)持久化
C++中對(duì)文件操作需要包含頭文件< fstream >
文件類型分為兩種:
1.?文本文件?- 文件以文本的ASCII碼形式存儲(chǔ)在計(jì)算機(jī)中
2. 二進(jìn)制文件-? 文件以文本的二進(jìn)制形式存儲(chǔ)在計(jì)算機(jī)中,用戶一般不能直接讀懂它們
操作文件的三大類:
1. ofstream : 寫操作
2.?ifstream : 讀操作
3. fstream : 讀寫操作
1.1 文本文件
1.1.1 寫文件
寫文件步驟如下:
1.包含頭文件
????????#include <fstream>
2.創(chuàng)建流對(duì)象
????????ofstream ofs;
3.打開文件
????????ofs.open("文件路徑",打開方式);
4.寫數(shù)據(jù)
????????ofs <<"寫入的數(shù)據(jù)";
5.關(guān)閉文件
????????ofs.close();
文件的打開方式:
打開方式 | 解釋 |
---|---|
ios::in | 為讀文件而打開文件 |
ios::out | 為寫文件而打開文件 |
ios::ate | 初始位置:文件尾 |
ios::app | 追加方式寫文件 |
ios::trunc | 如果文件存在先刪除,再創(chuàng)建 |
ios::binary | 二進(jìn)制方法 |
?
注意:文件打開方式可以配合使用,利用 | 操作符
例如:用二進(jìn)制方式寫文件
ios::binary | ios::out
#include <iostream>
#include <string>
#include <fstream>
using namespace std;//文本文件 寫文件
void test01() {//1、包含頭文件 fstream//2、創(chuàng)建流對(duì)象ofstream ofs;//3、打開方式ofs.open("test.txt", ios::out);//4、寫內(nèi)容ofs << "姓名:張三" << endl;ofs << "性別:男" << endl;ofs << "年齡:18" << endl;//5、關(guān)閉文件ofs.close();
}int main() {test01();return 0;
}
總結(jié):
·文件操作必須包含頭文件 fstream
·讀文件可以利用ofstream ,或者fstream類
·打開文件時(shí)候需要指定操作文件的路徑,以及打開方式
·利用<<可以向文件中寫數(shù)據(jù)
·操作完畢,要關(guān)閉文件
1.1.2 讀文件
讀文件與寫文件步驟相似,但是讀取方式相對(duì)于比較多
讀文件步驟如下:
1.包含頭文件
????????#include <fstream>
2.創(chuàng)建流對(duì)象
????????ifstream ifs;
3.打開文件并判斷文件是否打開成功
????????ifs.open("“文件路徑",打開方式);
4.讀數(shù)據(jù)
????????四種方式讀取
5.關(guān)閉文件
????????ifs.close();
#include <iostream>
#include <string>
#include <fstream>
using namespace std;//文本文件 讀文件
void test01() {//1、包含頭文件 fstream//2、創(chuàng)建流對(duì)象 ifstream ifs;//3、打開文件,并且判斷是否打開成功ifs.open("test.txt", ios::in);if (!ifs.is_open()) {cout << "文件打開失敗" << endl;return;}//4、讀數(shù)據(jù)//第一種/*char buf[1024] = {0};while (ifs >> buf) {cout << buf << endl;}*///第二種/*char buf[1024] = {0};while (ifs.getline(buf, sizeof(buf))) {cout << buf << endl;}*///第三種/*string buf;while (getline(ifs, buf)) {cout << buf << endl;}*///第四種 EOF->end of file 不推薦char c;while ((c = ifs.get()) != EOF) {cout << c;}//5、關(guān)閉文件ifs.close();
}int main() {test01();return 0;
}
總結(jié):
·讀文件可以利用ifstream ,或者fstream類
·利用is_open函數(shù)可以判斷文件是否打開成功
· close關(guān)閉文件
1.2 二進(jìn)制文件
以二進(jìn)制的方式對(duì)文件進(jìn)行讀寫操作
打開方式要指定為ios::binary?
1.2.1 寫文件
二進(jìn)制方式寫文件主要利用流對(duì)象調(diào)用成員函數(shù)write
函數(shù)原型:
ostream& write(const char * buffer,int len) ;
參數(shù)解釋:字符指針buffer指向內(nèi)存中一段存儲(chǔ)空間。len是讀寫的字節(jié)數(shù)
#include <iostream>
#include <string>
#include <fstream>
using namespace std;//二進(jìn)制文件 寫文件
class Person {
public://如果用二進(jìn)制進(jìn)行存儲(chǔ)這里最好用C語言的char類型char m_Name[64]; //姓名 int m_Age;
};void test01() {//1、包含頭文件//2、創(chuàng)建流對(duì)象ofstream ofs;//3、打開文件ofs.open("test.txt", ios::out | ios::binary);//4、寫文件Person p = { "張三",18 };//Person* 強(qiáng)轉(zhuǎn)為 const char*類型ofs.write((const char*)&p, sizeof(Person));//5、關(guān)閉文件ofs.close();}int main() {test01();return 0;
}
1.2.2 讀文件
二進(jìn)制方式讀文件主要利用流對(duì)象調(diào)用成員函數(shù)read
函數(shù)原型:
istream& read(char *buffer,int len);
參數(shù)解釋:字符指針buffer指向內(nèi)存中一段存儲(chǔ)空間。len是讀寫的字節(jié)數(shù)
#include <iostream>
#include <string>
#include <fstream>
using namespace std;//二進(jìn)制文件 讀文件
class Person {
public://如果用二進(jìn)制進(jìn)行存儲(chǔ)這里最好用C語言的char類型char m_Name[64]; //姓名 int m_Age;
};void test01() {//1、包含頭文件//2、創(chuàng)建流對(duì)象ifstream ifs;//3、打開文件 判斷文件是否打開成功ifs.open("test.txt", ios::in | ios::binary);if (!ifs.is_open()) {cout << "文件打開失敗" << endl;return;}//4、讀文件Person p;//Person* 強(qiáng)轉(zhuǎn)為 char* 類型ifs.read((char*)&p, sizeof(Person));cout << "姓名:" << p.m_Name << " 年齡:" << p.m_Age << endl;//5、關(guān)閉文件ifs.close();}int main() {test01();return 0;
}
文件輸入流對(duì)象可以通過read函數(shù),以二進(jìn)制方式讀數(shù)據(jù)
二、Python版
1、文件操作
在學(xué)習(xí)文件操作之前,先來回顧一下編碼的相關(guān)以及先關(guān)數(shù)據(jù)類型的知識(shí)。
·字符串類型(str),在程序中用于表示文字信息,本質(zhì)上是unicode編碼中的二進(jìn)制。
name = "武沛齊"
?·字節(jié)類型(bytes)
·可表示文字信息,本質(zhì)上是utf-8/gbk等編碼的二進(jìn)制(對(duì)unicode進(jìn)行壓縮,方便文件存儲(chǔ)和網(wǎng)絡(luò)傳輸)
name = "武沛齊"
data = name.encode('utf-8')
print(data) #b'\xe6\xad\xa6\xe6\xb2\x9b\xe9\xbd\x90'result = data.decode('utf-8')
print(result) #武沛齊
·可表示原始二進(jìn)制(圖片、文件等信息)
1.1 讀文件
·讀文本文件
"""
1.打開文件-路徑相對(duì)路徑:'info.txt'絕對(duì)路徑:r"D:\python的學(xué)習(xí)\題目\info.txt"-模式rb 表示讀取文件原始二進(jìn)制( r, 讀 read; b, 二進(jìn)制 binary)
"""#1、打開文件
file_object = open(r"D:\python的學(xué)習(xí)\題目\info.txt",mode='rb')#2、讀取文件
data = file_object.read()#3、關(guān)閉文件
file_object.close()print(data) #b'\xe5\xa7\x93\xe5\x90\x8d \xef\xbc\x9a \xe6\xad\xa6\xe6\xb2\x9b\xe9\xbd\x90'text = data.decode("utf-8")
print(text)
?改進(jìn):
#1、打開文件
# rt 讀取文本內(nèi)容
file_object = open("info.txt",mode='rt',encoding='utf-8')
#意思是 打開文件后 通過 utf-8 轉(zhuǎn)換后再讀取文本內(nèi)容#2、讀取文件
data = file_object.read()#3、關(guān)閉文件
file_object.close()print(data) #就是文件存儲(chǔ)的內(nèi)容了,無需decode
·讀圖片等非文本文件
#1、打開文件
file_object = open("a1.png",mode='rb')#2、讀取文件
data = file_object.read()#3、關(guān)閉文件
file_object.close()print(data)
若該文件不存在,會(huì)報(bào)錯(cuò)
?那如何判斷路徑是否存在呢:
import osexists = os.path.exists("info.txt") #返回的是 bool 值
print(exists) #True
1.2 寫文件
·寫文本文件
# 1、打開文件
# 路徑:相對(duì)/絕對(duì)
# 模式:wb (要求寫入的內(nèi)容需要是二進(jìn)制字節(jié)類型)
file_object = open("t1.txt", mode='wb')# 2、寫入內(nèi)容
file_object.write("武沛齊".encode("utf-8"))# 3、文件關(guān)閉
file_object.close()
改進(jìn):
# 1、打開文件
# 路徑:相對(duì)/絕對(duì)
# 模式:wt
# 如果不寫 encoding 會(huì)以默認(rèn)值 utf-8 寫入
file_object = open("t1.txt", mode='wt',encoding='utf-8')# 2、寫入內(nèi)容
file_object.write("武沛齊")# 3、文件關(guān)閉
file_object.close()
·寫圖片等文件
# 相當(dāng)于復(fù)制了一份
f1 = open("a1.png", mode='rb')
content = f1.read()
f1.close()f2 = open("a2.png", mode='wb')
f2.write(content)
f2.close()
注意的是,w寫入文件時(shí),先清空文件;再在文件中寫入內(nèi)容
而且如果路徑?jīng)]有該文件,w模式會(huì)新建然后再寫入內(nèi)容
所以如果你要寫入時(shí),在循環(huán)里實(shí)現(xiàn)寫入,循環(huán)前后只實(shí)現(xiàn)一次的打開和關(guān)閉
file_object = open('test.txt',mode='wt')while True:user = input("請(qǐng)輸入用戶名:")if user.upper() == "Q":breakpwd = input("請(qǐng)輸入密碼:")#data = "{}--{}\n".format(user,pwd)data = f"{user}--{pwd}\n"file_object.write(data)
file_object.close()
效果
wjw--123
pxy--456
1.3? ?文件打開方式
關(guān)于文件的打開模式常見應(yīng)用有:
r w x a 的默認(rèn)為 rt wt xt at
模式 | 文件存在 | 文件不存在 |
---|---|---|
只讀 r、rt、rb | 讀 | 報(bào)錯(cuò) |
只有 w、wt、wb | 清空再寫 | 創(chuàng)建再寫 |
只寫(了解即可) x、xt、xb | 報(bào)錯(cuò) | 創(chuàng)建再寫 |
只寫 a、at、ab 【尾部追加】 | 尾部追加 | 創(chuàng)建再寫 |
讀寫 | ||
r+、rb? ? ? ? 默認(rèn)光標(biāo)位置:起始位置 | ||
w+、wb????????默認(rèn)光標(biāo)位置:起始位置(清空文件) | ||
x+、xb????????默認(rèn)光標(biāo)位置:起始位置(新文件) | ||
a+、ab+????????默認(rèn)光標(biāo)位置:末尾 |
?
# rt+file_object = open("info.txt",mode="rt+",encoding='utf-8')
#讀取內(nèi)容
data = file_object.read()print(data)#寫入內(nèi)容
file_object.write("你好啊!")
file_object.close()
與
# rt+file_object = open("info.txt",mode="rt+",encoding='utf-8')#寫入內(nèi)容
file_object.write("你好啊!")#讀取內(nèi)容
data = file_object.read()print(data)file_object.close()
結(jié)果是不同的,這里與文件的光標(biāo)有關(guān)
rt+?默認(rèn)光標(biāo)位置是起始位置,如果先寫入就會(huì)往后覆蓋,再讀取的時(shí)候也會(huì)從光標(biāo)開始往后讀取
如果先讀取光標(biāo)會(huì)移至最后,然后再寫入
對(duì)于wt+
# wt+file_object = open("info.txt",mode="wt+",encoding='utf-8')#讀取內(nèi)容,由于wt+會(huì)清空內(nèi)容,所以必定為空
data = file_object.read()
print(data)#寫入內(nèi)容,此時(shí)寫入后光標(biāo)會(huì)移至最后
file_object.write("你好啊!")#再想讀取內(nèi)容,光標(biāo)要移至最前面,就ok了
file_object.seek(0)
data = file_object.read()
print(data)file_object.close()
對(duì)于at+
# at+file_object = open("info.txt",mode="at+",encoding="utf-8")#寫入內(nèi)容,at+光標(biāo)開始在最后,直接末尾追加
file_object.write("你好啊!")#想讀取內(nèi)容,光標(biāo)要移至最前面,就ok了
file_object.seek(0)
data = file_object.read()
print(data)file_object.close()
1.4 常見功能
在上述對(duì)文件的操作中,我們只使用了write和read來對(duì)文件進(jìn)行讀寫,其實(shí)在文件操作中還有很多其他的功能來輔助實(shí)現(xiàn)更好的讀寫文件的內(nèi)容。
1、read,讀所有
f = open('info.txt',mode='r',encoding='utf-8')
data = f.read()
print(data)
2、read,讀一個(gè)字符(三個(gè)字節(jié))
f = open('info.txt',mode='r',encoding='utf-8')
data = f.read(1)
f.close()
print(data)
3、read,讀一個(gè)字節(jié)
f = open('info.txt',mode='rb')
data = f.read(1)
f.close()
print(data)
4、readline,讀一行
f = open('info.txt',mode='r',encoding='utf-8')
data = f.readline()print(data)f.close()
5、readlines,讀所有行,每行作為列表的一個(gè)元素
f = open('info.txt',mode='r',encoding='utf-8')
data = f.readlines()print(data)f.close()
6、循環(huán),讀大文件(readline加強(qiáng)版)
while循環(huán)難以判斷其終止操作,所以用 for
f = open('info.txt',mode='r',encoding='utf-8')for line in f:print(line.strip())f.close()
7、flush,刷到硬盤
f = open('info.txt',mode='w',encoding='utf-8')for i in range(0,3):#不是寫到了硬盤,而是寫在緩沖區(qū),系統(tǒng)會(huì)將緩沖區(qū)的內(nèi)容刷到硬盤f.write("你好啊!")#寫上flush之后,立即刷到y(tǒng)ingpanlf.flush()print(1)f.close()
8、seek() 移動(dòng)光標(biāo)位置(字節(jié))
f = open('info.txt',mode='r+',encoding='utf-8')#移動(dòng)光標(biāo)位置,在次光標(biāo)之后開始寫內(nèi)容,如果有內(nèi)容,則會(huì)覆蓋
#移動(dòng)到指定字節(jié)的位置,最好是3的倍數(shù),否則會(huì)發(fā)生亂碼的情況
f.seek(3)
f.write("中國(guó)")f.close()
注意︰在a模式下,調(diào)用write在文件中寫入內(nèi)容時(shí),永遠(yuǎn)只能將內(nèi)容寫入到尾部,不會(huì)寫到光標(biāo)的位置。
9、tell() 獲取當(dāng)前光標(biāo)的位置
f = open('info.txt', mode='r+', encoding='utf-8')p1 = f.tell()
print(p1) # 0
f.read(2) # 讀取的是字符 2 * 3 個(gè)字節(jié)
p2 = f.tell()
print(p2) # 6f.close()
f = open('info.txt', mode='rb')p1 = f.tell()
print(p1) # 0
f.read(3) # 讀取的是3 個(gè)字節(jié)
p2 = f.tell()
print(p2) # 3f.close()
1.5 上下文管理
之前對(duì)文件進(jìn)行操作時(shí),每次都要打開和關(guān)閉文件,比較繁瑣且容易忘記關(guān)閉文件。以后再進(jìn)行文件操作時(shí),推薦大家使用with上下文管理,它可以自動(dòng)實(shí)現(xiàn)關(guān)閉文件。
writh open ( ”xxXX,txt" , mode= "rb" ) as file_object :data = file_object.read()print (data)
在Python 2.7后,with又支持同時(shí)對(duì)多個(gè)文件的上下文進(jìn)行管理,即:
with open (“x展x據(jù).txt",mode="rb") as f1,open ( "%x×xtxt”,mode="rb" ) as f2:pass
2、CSV格式文件
逗號(hào)分隔值(Comma-separated Values,CSV,有時(shí)也稱為字符分隔值,因?yàn)榉指糇址部梢圆皇嵌禾?hào)),其文件以純文本形式存儲(chǔ)表格數(shù)據(jù)(數(shù)字和文本)。對(duì)于這種格式的數(shù)據(jù),我們需要利用open函數(shù)來讀取文件并根據(jù)逗號(hào)分隔的特點(diǎn)來進(jìn)行處理。
股票代碼,股票名稱,當(dāng)前價(jià),漲跌額,漲跌幅,年初至今
601778,t晶科,6.29,+1.92 ,-43.94%,+43.948%
688566,吉貝爾。52.66,+6.96,+15.238,+122.29....
with open('cs.csv', mode='r',encoding='utf-8') as f:f.readline()for line in f:id,year,bl = line.strip().split(',')print(id,year)
3、ini格式
ini文件是Initialization File的縮寫,平時(shí)用于存儲(chǔ)軟件的的配置文件。例如:MySQL數(shù)據(jù)庫的配置文件。
[DataBase]
ServerIP=**********
ServerPort=8080
ControlConnectString=QWDJ7+XH6oWaANAGhVgh5/5UxYrA2rfz/ufAkDlN1H9Tw+v7Z0SoCfR+wYdyzCjF/ANUfPxlO6cLDAhm4xxmbADyKs6zmkWuGQNgDZmPx6c=
ControlConnectCategory=0
?
[LogonInfo]
SaveUserID=Y
UserID=admin
DBServer=AppDB
DBCenter=Demo
?
[UserConfig]
OpenDownloadFileAtOnec=Y
WindowStyle=DevExpress Dark Style
?
[Language]
Language=CHS
?
?
[AutoUpdate]
Version=1.1
?這種格式是可以直接使用open來出來,考慮到自己處理比較麻煩,所以Python為我們提供了更為方便的方式。
3.1 讀取所有節(jié)點(diǎn)
import configparserconfig = configparser.ConfigParser()
config.read('in.ini',encoding='utf-8')#獲取節(jié)點(diǎn),列表形式
result = config.sections()
print(result)
3.2 讀取節(jié)點(diǎn)下的鍵值
import configparserconfig = configparser.ConfigParser()
config.read('in.ini',encoding='utf-8')#該節(jié)點(diǎn)下的鍵值,返回的是列表里的元組
result = config.items('LogonInfo')
print(result)
3.3 獲取某個(gè)節(jié)點(diǎn)下的鍵值對(duì)應(yīng)的值
import configparserconfig = configparser.ConfigParser()
config.read('in.ini',encoding='utf-8')result = config.get("UserConfig","WindowStyle")
print(result)
3.4 其他
import configparserconfig = configparser.ConfigParser()
config.read('in.ini',encoding='utf-8')#判斷是否有該節(jié)點(diǎn)
v1 = config.has_section("UserConfig")
print(v1)#增加一個(gè)節(jié)點(diǎn)
config.add_section("group")
#此時(shí)并未寫入,所以要寫write(),這里可以換別的名字,重新創(chuàng)建一個(gè)文件
config.write(open('in.ini',mode='w',encoding='utf-8'))#增加鍵值
config.set("group","name","wjw")
config.write(open('in.ini',mode='w',encoding='utf-8'))#刪除節(jié)點(diǎn)
config.remove_section('Language')
config.write(open('in.ini',mode='w',encoding='utf-8'))#刪除鍵值
config.remove_option("LogonInfo","userid")
config.write(open('in.ini',mode='w',encoding='utf-8'))
4、XML格式文件
? ? ? ? 暫時(shí)用不到哈,先不學(xué)了
5、Excel格式文件
Python內(nèi)部未提供處理Excel文件的功能,想要在Python中操作Excel需要按照第三方的模塊。
pip install openpyxl
此模塊中集成了Python操作Excel的相關(guān)功能,接下來我們就需要去學(xué)習(xí)該模塊提供的相關(guān)功能即可。
5.1 讀文件
1.讀sheet
from openpyxl import load_workbookwb = load_workbook("1.xlsx")#1、獲取excel文件中的所有sheet名稱
#print(wb.sheetnames) #['sheet2', 'Sheet1']#2、選擇sheet,基于sheet名稱
"""
sheet = wb["Sheet1"]
#讀取單元格
cell = sheet.cell(1,1)
print(cell.value)
"""#3、選擇sheet,基于索引位置
"""
sheet = wb.worksheets[0]
cell = sheet.cell(3,1)
print(cell.value)
"""#4、循環(huán)所有的sheet
"""
for name in wb.sheetnames:sheet = wb[name]cell = sheet.cell(3,1)print(cell.value)
"""
"""
for sheet in wb.worksheets:cell = sheet.cell(3, 1)print(cell.value)
"""
for sheet in wb:cell = sheet.cell(3,1)print(cell.value)
from openpyxl import load_workbookwb = load_workbook("1.xlsx")
sheet = wb.worksheets[0]#1、獲取第N行第N列的單元格
"""
cell = sheet.cell(3,1)
print(cell.value)
print(cell.font)
print(cell.style)
print(cell.alignment) #排列情況
"""#2、獲取某個(gè)單元格
"""
c1 = sheet["B3"]
print(c1.value)c2 = sheet["C4"]
print(c2.value)
"""#3、第N行所有的單元格
"""
for cell in sheet[3]:print(cell.value)
"""#4、所有行的數(shù)據(jù)
"""
for row in sheet.rows:#獲得的是元組print(row[2].value)
"""#5、所有列的數(shù)據(jù)
"""
for col in sheet.columns:print(col[2].value)
"""
2.讀合并的單元格
?
from openpyxl import load_workbookwb = load_workbook("1.xlsx")
sheet = wb.worksheets[1]c1 = sheet.cell(1,1)
print(c1.value) #測(cè)試數(shù)據(jù)c2 = sheet.cell(1,2)
print(c2.value) #None
?合并單元格顯示最前面的,其他的都置為空
5.2 寫Excel
在Excel中想要寫文件,大致要分為
1.原Excel文件基礎(chǔ)上寫內(nèi)容
from openpyxl import load_workbookwb = load_workbook("1.xlsx")
sheet = wb.worksheets[1]# 找到單元格,并修改單元的內(nèi)容
cell = sheet.cell(9,1)
cell.value = "wjm"#將excel文件保存到2.xlsl文件中
wb.save("2.xlsx")
2.新創(chuàng)建Excel文件寫內(nèi)容
from openpyxl import workbook#創(chuàng)建excel且默認(rèn)會(huì)創(chuàng)建一個(gè)sheet(名稱為Sheet)
wb = workbook.Workbook()sheet = wb.worksheets[0] #或 sheet = wb["Sheet"]#找到單元格,并修改單元格的內(nèi)容
cell = sheet.cell(1,1)
cell.value = "新的開始"#將excel文件保存到3.xlsx文件中
wb.save("3.xlsx")
拓展:
from openpyxl import workbookwb = workbook.Workbook()#1、修改sheet名稱
"""
sheet = wb.worksheets[0]
sheet.title = "數(shù)據(jù)集"
wb.save ( "p2.xlsx")
"""#2、創(chuàng)建sheet并設(shè)置sheet顏色
"""
sheet = wb.create_sheet("工作計(jì)劃",0)
sheet.sheet_properties.tabcolor = "1072BA"
wb.save("p2.xlsx")
"""#3、默認(rèn)打開的sheet
"""
wb.active = o
wb.save("p2.xlsx")
"""#4、拷貝sheet
"""
sheet = wb.create_sheet ("工作計(jì)劃")
sheet.sheet_properties.tabColor = "1072BA"
new_sheet = wb.copy_worksheet(wb["sheet"])
new_sheet.title = "新的計(jì)劃"
wb.save("p2.xlsx")
"""#5、刪除sheet
"""
del wb["用戶列表"]
wb.save("p2.xlsx")
"""
還有
from openpyxl import load_workbook
from openpyxl.styles import Alignment, Border, Side, Font, PatternFill, GradientFillwb = load_workbook("1.xlsx")
sheet = wb.worksheets[0]# 1.獲取某個(gè)單元格,修改值
"""
cell = sheet.cell(1,1)
cell.value = "開始"
wb.save("2.xlsx")
"""# 2.獲取某個(gè)單元格,修改值
"""
sheet["B2"]= "開始"
wb.save("2.xlsx")
"""# 3.獲取某些單元格,修改值
"""
cell_list = sheet["B2":"C3"] #4個(gè)單元格
#(
# (單元格,單元格)
# (單元格,單元格)
#)
for row in cell_list:for cell in row:cell.value = "新的值"
wb.save("2.xlsx")
"""# 4.對(duì)齊方式
"""
cell = sheet.cell(1,1)
#horizontal 水平方向?qū)R方式:general left center right fill justify centerContinous distributed
#vertical 垂直方向?qū)R方式:top center bottom justify distributed
#text_rotation 旋轉(zhuǎn)角度
#wrap_text 是否自動(dòng)換行
cell.alignment = Alignment(horizontal='center',vertical='center',text_rotation=45,wrap_text=True)
wb.save("2.xlsx")
"""# 5.邊框
# side 的 style 如下:dashDot dashDotDot dashed dotted double hair medium mediumDashDot mediumDashDot mediumDashed slantDashDot thick thin
"""
cell = sheet.cell(9,2)
cell.border = Border(top = Side(style="thin",color="FFB6C1"),bottom=Side(style="dashed",color="FFB6C1"),left=Side(style="dashed",color="FFB6C1"),right=Side(style="dashed",color="9932cC"),diagonal=Side(style="thin",color="483D8B"),#對(duì)角線diagonalup=True, #左下 ~右上dliagonalDown=True #左上 –右下
)
wb.save("2.xlsx")
"""# 6.字體
"""
cell = sheet.cell(5,1)
cell.font = Font(name="微軟雅黑",size=45,color="ff0000",underline="single")
wb.save("2.xlsx")
"""# 7.背景色
"""
cell = sheet.cell(5,1)
cell.fill = PatternFill("solid",fgColor="99ccff")
wb.save("2.xlsx")
"""# 8.漸變背景色
"""
cell = sheet.cell(5,1)
cell.fill = GradientFill("linear",stop=("FFFFFF","99ccff","000000"))
wb.save("2.xlsx")
"""# 9.寬高 (索引從1開始)
"""
sheet.row_dimensions[1].height = 50
sheet.columns_dimensions["E"].width = 100
wb.save("2.xlsx")
"""# 10.合并單元格
"""
sheet.merge_cells("B2:D8")
sheet.merge_cells(start_row=15,start_column=3,end_row=18,end_column=8)
wb.save("2.xlsx")
"""# 11.寫入公式
"""
sheet = wb.worksheets[1]
sheet["D1"] = "合計(jì)"
sheet["D2"] = "=B2*C2"
wb.save("2.xlsx")
"""
"""
sheet = wb.worksheets[1]
sheet["D3"] = "=SUM(B3,C3)"
wb.save("2.xlsx")
"""# 12.刪除
"""
#idx. 要?jiǎng)h除的索引位置
#amount 從索引位置開始要?jiǎng)h除的個(gè)數(shù)(默認(rèn)為1)
sheet.delete_cols(idx=1,amount=1)
sheet.delete_rows(idx=1,amount=2)
wb.save("2.xlsx")
"""# 13.插入
"""
sheet.insert_cols(idx=5,amount=10)
sheet.insert_rows(idx=3,amount=2)
wb.save("2.xlsx")
"""# 14.循環(huán)寫內(nèi)容
"""
sheet = wb["Sheet"]
cell_range = sheet["A1:C2"]
for row in cell_range:for cell in row:cell.value = "xx"for row in sheet.iter_rows(min_row=5,min_col=1,max_row=7,max_col=10):for cell in row:cell.value = "oo"
wb.save("2.xlsx")
"""# 15.移動(dòng)
"""
# 將H2:J10范圍的數(shù)據(jù),向右移動(dòng)15個(gè)位置、向上移動(dòng)1個(gè)位置
sheet.move_range("H2:J10", rows=-1, cols=15)
wb.save("p2.xlsx")
"""
"""
sheet = wb.worksheets[3]
sheet["D1"] = "合計(jì)"
sheet["D2"] = "=SUM(B3,C3)"
sheet.move_range("B1:D3",cols=10,translate=True)#自動(dòng)翻譯公式
wb.save("2.xlsx")
"""#16.打印區(qū)域
"""
sheet.print_area = "A1:D200"
wb.save("2.xlsx")
"""#17.打印時(shí),每個(gè)頁面的固定表頭
"""
sheet.print_title_cols = "A:D"
sheet.print_title_rows = "1:3"
wb.save("2.xlsx")
"""
你以為結(jié)束了嗎?
并沒有,因?yàn)槲覍W(xué)??嫉氖荂SV文件我們要用csv模板,Excel用 xlrd 和 xlwt 模板學(xué)習(xí),下面我們繼續(xù)學(xué)習(xí)
CSV
1.導(dǎo)入模塊
Python有內(nèi)置CSV模塊,導(dǎo)入這個(gè)模塊后,可以很輕松讀取CSV文件。
import csv
讀寫文件
·open()打開文件使用完畢后必須close()關(guān)閉,因?yàn)槲募?duì)象會(huì)占用操作系統(tǒng)的資源,并且操作系統(tǒng)同一時(shí)間能打開的文件數(shù)量也是有限的
·with open(x) as x:打開的文件使用關(guān)閉后不需要主動(dòng)關(guān)閉文件。因?yàn)閣ith語句的上下文管理器會(huì)幫助處理。這在操作資源文件時(shí)非常方便,因?yàn)樗艽_保在代碼執(zhí)行完畢后資源會(huì)被釋放掉
2.讀取CSV文件
1.使用open()打開CSV文件
csvFile = open(文件名) #打開文件建立 CSV 文件對(duì)象 csvFile
?2.使用with打開CSV文件
with open(文件名)as csvFile: # csvFi1e是可以自行命名的文件對(duì)象
? ? ? ? ....
?2.1.建立reader對(duì)象
·有了CSV文件對(duì)象后,下一步可以使用c5v模塊的 reader()建立 reader對(duì)象,可以使用list()將這個(gè)reader 對(duì)象轉(zhuǎn)換成列表(list),現(xiàn)在我們可以很輕松地使用這個(gè)列表資料了。
import csvfn = 'cs.csv'
with open(fn) as csvFile: #打開csv文件csvReader = csv.reader(csvFile) #讀文件建立Reader對(duì)象
2.2 讀取CSV文件
import csvfn = 'cs.csv'
with open(fn) as csvFile: #打開csv文件csvReader = csv.reader(csvFile) #讀文件建立Reader對(duì)象listReport = list(csvReader) #將數(shù)據(jù)轉(zhuǎn)換為列表print(listReport[0][1])#打印即可
?3.1.建立writer對(duì)象
import csvfn = 'cs.csv'
with open(fn,"w") as csvFile: #打開csv文件csvWriter = csv.writer(csvFile) #寫文件建立writer對(duì)象
3.2 寫入CSV文件
import csvfn = 'cs.csv'
with open(fn,"w") as csvFile: #打開csv文件csvWriter = csv.writer(csvFile) #寫文件建立writer對(duì)象csvWriter.writerow(['Name',"Age","City"])csvWriter.writerow(['wjw','25','TaiBei'])
EXCEL
方式 | 功能 | 文件格式 |
---|---|---|
xlrd | 只能讀 | xls , xlsx |
xlwt | 只能寫 | 只能xls格式 |
?xlrd
import xlrd
#打開文件
book = xlrd.open_workbook('1.xlsx')
#讀取指定sheet:print(book.sheets())#獲取全部sheetsheet = book.sheet_by_index(0) #根據(jù)索引獲取工作表sheet = book.sheet_by_name("Sheet1") #根據(jù)sheetname進(jìn)行獲取print(book.sheet_names())#獲取所有工作表nameprint(book.nsheets)#返回工作表數(shù)量
#獲取行和列數(shù)
rows = sheet.nrows
cols = sheet.ncols
操作行
import xlrd#打開文件
book = xlrd.open_workbook('1.xlsx')#操作excel行
sheet=book.sheet_by_index(1)#獲取第一個(gè)工作表
print(sheet.nrows)#獲取sheet下的有效行數(shù)
print(sheet.row(1))#該行單元格對(duì)象組成的列表
print(sheet.row_types(2))#獲取單元格的數(shù)據(jù)類型
print(sheet.row(1)[2].value)#得到單元格value
print(sheet.row_vaiues(1))#得到指定行單元格的value
print(sheet.row_values(1))#得到指定行單元格的value
print(sheet.row_len(1))#得到單元格的長(zhǎng)度
操作列
import xlrd#打開文件
book = xlrd.open_workbook('1.xlsx')#操作excel列
sheet=book.sheet_by_index(1)#獲取第一個(gè)工作表
print(sheet.ncols)#獲取sheet下的有效列數(shù)
print(sheet.col(1))#該行單元格對(duì)象組成的列表
print(sheet.col_types(2))#獲取單元格的數(shù)據(jù)類型
print(sheet.col(1)[2].value)#得到單元格value
print(sheet.col_vaiues(1))#得到指定列單元格的value
print(sheet.col_values(1))#得到指定列單元格的value
print(sheet.col_len(1))#得到單元格的長(zhǎng)度
操作Excel單元格
import xlrd#打開文件
book = xlrd.open_workbook('1.xlsx')#操作Excel單元格
sheet=book.sheet_by_index(0)
print(sheet.cell(1,2))
print(sheet.cell_type(1,2))
print(sheet.cell(1,2).ctype) #獲取單元格數(shù)據(jù)類型
print(sheet.cell(1,2).value)
print(sheet.cell_value(1,2))
xlwt
import xlwttitlestyle = xlwt.XFStyle() #初始化樣式
titlefont = xlwt.Font()
titlefont.name = "宋體"
titlefont.bold = True #加粗
titlefont.height = 11*20 #字號(hào)
titlefont.colour_index = 0x08 #設(shè)置字體顏色
titlestyle.font = titlefont#單元個(gè)對(duì)齊方式
cellalign = xlwt.Alignment()
cellalign.horz = 0x02
cellalign.vert = 0x01
titlestyle.alignment = cellalign#邊框
borders = xlwt.Borders()
borders.right=xlwt.Borders.DASHED
borders.bottom=xlwt.Borders.DOTTED
titlestyle.borders = borders#
datestyle = xlwt.XFStyle()
bgcolor = xlwt.Pattern()
bgcolor.pattern = xlwt.Pattern.SOLID_PATTERN
bgcolor.pattern_fore_colour = 22 #背景顏色
datestyle.pattern = bgcolor#第一步:創(chuàng)建工作簿
wb=xlwt.Workbook()
#第二步:創(chuàng)建工作表
ws=wb.add_sheet("CNY")
#第三步:填充數(shù)據(jù)
ws.write_merge(0,1,0,5,"2019年貨幣兌換表",titlestyle)
#寫入貨幣數(shù)據(jù)
data = (("Date","英鎊","人民幣","港幣","日元","美元"),("01/01/2019",8.722551,1,0.877885,0.062722,6.8759),("02/01/2019",8.634922,1,0.875731,0.062773,6.8601))
for i , item in enumerate(data):
#enumerate 包含索引for j , val in enumerate(item):if j==0:ws.write(i + 2, j, val,datestyle)else:ws.write(i + 2,j,val)#第四步:保存
wb.save("2019-CNY.xls")