目錄
os子產品的使用
open("test.txt","mode")
讀取檔案中的内容
f.read()
f.readline(size)
f.readlines(size)
寫入資料到檔案中
追加資料
覆寫原資料
讀寫檔案的IO指針的一些問題
os子產品中一些基本的判斷檔案的函數
CSV子產品的使用
讀檔案
reader(csvfile, dialect='excel', **fmtparams)
讀取指定的列
DictReader函數是傳回字典格式的資料
讀取指定列的資料
寫檔案
writer(csvfile, dialect='excel', **fmtparams)
追加一行資料進去
覆寫之前的資料
xlrd子產品
OS子產品簡單的來說它是一個Python的系統程式設計的操作子產品,可以處理檔案和目錄
以下都是python3.7環境下
os子產品的使用
open("test.txt","mode")
mode有以下幾種:
- r : 隻讀,如果無此檔案的話就會報錯
- r+: 讀寫方式打開,既可讀也可寫
- w: 寫入,覆寫之前的内容,如果無此檔案就建立,隻能寫不能讀
- a: 寫入,在檔案末尾追加新的内容,檔案如果不存在,則建立,隻能寫不能讀
- +: 更新,須結合 r、w、a 參數使用,指針在最後面
- b: 打開二進制的檔案,可以與 r、w、a、+ 結合使用
- U:支援所有的換行符号。“ \r ”、“ \n ", " \r\n "
注:r 、w 、a 不能結合使用。不寫mode參數預設是隻讀
兩種打開檔案的方式
f=open("test.txt","r")
或
with open("test.txt","r") as f:
如果是讀取其他路徑下的檔案的話
open("c://users//desktop//test.txt")
open("c:\\users\\desktop\\test.txt")
open("c:\/users\/desktop\/test.txt")
現在有一個 test.txt 檔案,裡面有以下内容
hello,word!
iloveyou
xiaoxie
讀取檔案中的内容
不管用什麼方法讀取檔案中的内容,隻要不是檔案的最後一行,其他行的末尾都會有一個 \n 。上面檔案的内容,如果讀取的話,在讀取的字元串中實際上是這樣的。是以我們在讀取檔案内容的時候,都會對檔案去除\n ,使用字元串的 strip() 方法
hello,word!\n
iloveyou\n
xiaoxie
f.read()
函數,讀取檔案中的所有内容,傳回一個 str 字元串
import os
try:
with open("test.txt",'r') as f:
a=f.read()
print(a)
print(type(a))
print(len(a))
except Exception as e:
print("異常對象的類型是:%s"%type(e))
print("異常對象的内容是:%s"%e)
finally:
f.close()
##########################################################
hello,word!
iloveyou
xiaoxie
<class 'str'>
28
明明是26位元組,為什麼列印出來是28位元組呢?這是因為第一行和第二行的 \n 也被算成了一個字元
f.readline(size)
函數,讀取檔案的第一行内容,傳回一個字元串,參數size代表讀取的字元串長度,不填預設讀取所有第一行所有内容,包括 \n
import os
try:
with open("test.txt",'r') as f:
a=f.readline() #讀取檔案的第一行
print(a)
print(type(a))
print(len(a))
except Exception as e:
print("異常對象的類型是:%s"%type(e))
print("異常對象的内容是:%s"%e)
finally:
f.close()
####################
hello,word!
<class 'str'>
12
這裡為什麼第二行是空的呢,字元串長度是12呢?這是因為第一行末尾還有一個 \n , 這是換行符,是以第二行是空的,也是以字元串長度讀成了12,要想改成,我們可以修改下面幾行,這樣列印出來的就正常了
print(a.strip('\n'))
print(type(a))
print(len(a.strip('\n')))
########
hello,word!
<class 'str'>
11
f.readlines(size)
函數讀取檔案中的内容,參數size代表讀取的行數,不填預設讀取所有行,傳回一個 list 清單,每一行作為清單的一個值
這裡要注意的是,如果要列印出每行的内容的話,要用 str.strip() 方法把末尾的 \n 給去掉
import os
try:
with open("test.txt",'r') as f:
lines=f.readlines()
print(lines,type(lines))
for line in lines:
print(line.strip('\n'),end='---')
print(len(line.strip('\n')))
except Exception as e:
print("異常對象的類型是:%s"%type(e))
print("異常對象的内容是:%s"%e)
finally:
f.close()
######################
['hello,word!\n', 'iloveyou\n', 'xiaoxie'] <class 'list'>
hello,word!---11
iloveyou---8
xiaoxie---7
寫入資料到檔案中
- f.write(str) 的參數是一個字元串,就是你要寫入的内容
- f.writelines(sequence)的參數是序列,比如清單,它會疊代幫你寫入檔案。但是序列中的元素也必須是str字元串
追加資料
預設我們寫入的資料是在原資料的末尾的,也就是不是新的一行。如果我們想一行一行寫入,我們可以在寫入每一行之前,先寫入 \n
import os
try:
with open("test.txt",'a',encoding='utf-8') as f:
f.write("\n")
f.write("nihao")
except Exception as e:
print("異常對象的類型是:%s"%type(e))
print("異常對象的内容是:%s"%e)
finally:
f.close()
覆寫原資料
import os
try:
with open("test.txt",'w',encoding='utf-8') as f:
f.write("nihao")
f.write("\n")
except Exception as e:
print("異常對象的類型是:%s"%type(e))
print("異常對象的内容是:%s"%e)
finally:
f.close()
還有一種利用print寫入資料,知道就好,不常用
import os
f=open("test.txt","w",encoding='utf-8')
print("hello,word!",file=f) #将hello,word!追加寫入test.txt檔案中
f.close()
讀寫檔案的IO指針的一些問題
比如我們有一個檔案 test.txt 裡面的内容是: hello,word!
import os
with open("test.txt","r") as f:
print("*"*50)
print(f.read())
print("*"*50)
print(f.read())
print("*"*50)
f.close()
**************************************************
hello,word!
**************************************************
**************************************************
我們可以看到,第二次列印什麼東西也沒列印出來。那是因為我們第一次讀取檔案的時候,我們的指針已經到檔案的末尾了,當我們再次讀取檔案的時候,自然就沒有東西了。除非我們關閉檔案流,再次打開讀取。
os子產品中一些基本的判斷檔案的函數
os.getcwd() 傳回目前工作路徑
os.chdir("e://") 修改工作路徑
open("test.txt","w") 建立檔案
os.remove("test.txt") 删除檔案
os.mkdir("e://test") 在目前目錄下建立目錄
os.rmdir("e://test") 删除給定路徑的目錄(該目錄必須是空目錄,不然報錯)
os.removedirs("e://test") 删除給定路徑的目錄(該目錄必須是空目錄,不然報錯)
os.listdir("e://") 傳回給定路徑下的所有檔案和目錄,傳回的是清單類型的資料
os.path.abspath("123.txt") 擷取目前目錄下某檔案的絕對路徑,如果該檔案不存在,也傳回路徑
os.path.exists("123") 判斷該目錄下檔案或者目錄是否存在,如果存在傳回true,否則傳回false
如果存在,則再判斷是目錄還是檔案,如果存在傳回true,否則傳回false
os.path.isdir("123") 判斷是否是目錄
os.path.isfile("123") 判斷是否是檔案
os.path.isabs("c://users//") 判斷給定的路徑是絕對路徑還是相對路徑,絕對路徑是話傳回True,相對路徑傳回False。他不會去判斷你給定的路徑是否真實存在
os.path.split("c://users//test.txt") 将給定路徑的路徑和檔案名分隔開,傳回元組型資料 ('c://users', 'test.txt')
os.path.split("c://users//test.txt")[0] 傳回給定路徑的路徑名 c://users
os.path.dirname("c://users/test.txt") 傳回給定路徑的路徑名 c://users
os.path.split("c://users//test.txt")[1] 傳回給定路徑的檔案名 test.txt
os.path.basename("c://users//test.txt") 傳回給定路徑的檔案名 test.txt
path=os.path.join("c:// ",123.txt) 将路徑和檔案名加在一起
執行個體:遞歸列印出給定路徑下的所有檔案
#遞歸列印出給定路徑内的所有檔案
import os
def Test(path):
lines=os.listdir(path)
for line in lines:
pathname=os.path.join(path,line)
if os.path.isdir(pathname): #如果是目錄的話
print("這是目錄:",pathname)
Test(pathname) #再遞歸調用該函數
else:
print(pathname) #如果是檔案
Test("g://xie")
CSV子產品的使用
CSV (Comma Separated Values) 即逗号分隔值(也稱字元分隔值,因為分隔符可以不是逗号),是一種常用的文本格式,用以存儲表格資料,包括數字或者字元。很多程式在處理資料時都會碰到csv這種格式的檔案,它的使用是比較廣泛的,python内置了處理csv格式資料的csv子產品。
讀檔案
比如我們現在有一個 test.csv的檔案,檔案内容如下
我們使用reader函數來讀取 test.csv 檔案中的内容
reader(csvfile, dialect='excel', **fmtparams)
- csvfile 參數,必須是支援疊代(Iterator)的對象,可以是檔案(file)對象或者清單(list)對象,如果是檔案對象,打開時需要加"b"标志參數。
- dialect參數,編碼風格,不寫則預設為excel的風格,也就是用逗号(,)分隔,dialect方式也支援自定義,通過調用register_dialect方法來注冊
- fmtparams參數,格式化參數,用來覆寫之前dialect對象指定的編碼風格。
import csv
try:
with open("test.csv","r") as f:
lines=csv.reader(f) #傳回的是 _csv.reader 對象
print(lines,type(lines))
for line in lines:
print(line,type(line)) #傳回的每一行是清單格式
except Exception as e:
print("異常對象的類型是:%s"%type(e))
print("異常對象的内容是:%s"%e)
finally:
f.close()
#########################
<_csv.reader object at 0x00000141BEC9E938> <class '_csv.reader'>
['id', 'name', 'age'] <class 'list'>
['1', 'xie', '20'] <class 'list'>
['2', 'xiao', '30'] <class 'list'>
['3', 'wang', '40'] <class 'list'>
['4', 'li', '50'] <class 'list'>
讀取指定的列
import csv
try:
with open("test.csv","r") as f:
lines=csv.reader(f)
for line in lines:
print(line[1],type(line[1])) ##傳回的是字元串
except Exception as e:
print("異常對象的類型是:%s"%type(e))
print("異常對象的内容是:%s"%e)
finally:
f.close()
##########################
name <class 'str'>
xie <class 'str'>
xiao <class 'str'>
wang <class 'str'>
li <class 'str'>
DictReader函數是傳回字典格式的資料
import csv
try:
with open("test.csv","r") as f:
lines=csv.DictReader(f) #傳回的是 _csv.reader 對象
print(lines,type(lines))
for line in lines:
print(line,type(line)) #傳回的每一行是清單格式
except Exception as e:
print("異常對象的類型是:%s"%type(e))
print("異常對象的内容是:%s"%e)
finally:
f.close()
##########################
<csv.DictReader object at 0x000001E63C477668> <class 'csv.DictReader'>
OrderedDict([('id', '1'), ('name', 'xie'), ('age', '20')]) <class 'collections.OrderedDict'>
OrderedDict([('id', '2'), ('name', 'xiao'), ('age', '30')]) <class 'collections.OrderedDict'>
OrderedDict([('id', '3'), ('name', 'wang'), ('age', '40')]) <class 'collections.OrderedDict'>
OrderedDict([('id', '4'), ('name', 'li'), ('age', '50')]) <class 'collections.OrderedDict'>
讀取指定列的資料
import csv
try:
with open("test.csv","r") as f:
lines=csv.DictReader(f) #傳回的是 _csv.reader 對象
col=[line['name'] for line in lines]
print(col,type(col))
except Exception as e:
print("異常對象的類型是:%s"%type(e))
print("異常對象的内容是:%s"%e)
finally:
f.close()
##################################
['xie', 'xiao', 'wang', 'li'] <class 'list'>
寫檔案
writer(csvfile, dialect='excel', **fmtparams)
- csvfile 參數,必須是支援疊代(Iterator)的對象,可以是檔案(file)對象或者清單(list)對象
- dialect參數,編碼風格,預設為excel的風格,也就是用逗号(,)分隔,dialect方式也支援自定義,通過調用register_dialect方法來注冊
- fmtparams參數,格式化參數,用來覆寫之前dialect對象指定的編碼風格。
寫入資料時傳入的資料,可以是元組,也可以是清單,他會自動把元組或清單中的資料寫進不同列中。
追加一行資料進去
import csv
row=['5','zhang','60']
try:
with open("test.csv","a",newline='') as f:
csv_writer=csv.writer(f)
csv_writer.writerow(row)
except Exception as e:
print("異常對象的類型是:%s"%type(e))
print("異常對象的内容是:%s"%e)
finally:
f.close()
注:python3 和 python2 這個子產品的使用有點不同。python3寫入為了防止空一行,會在加一個 newline 參數。python2的話,則是寫入方式加一個b
python3:with open("test.csv","a",newline='') as f:
python2:with open("test.csv","ab") as f:
覆寫之前的資料
import csv
try:
with open("test.csv","w",newline='') as f:
csv_writer=csv.writer(f)
csv_writer.writerow(["id","name","age"])
csv_writer.writerow(["1","xie","20"])
csv_writer.writerow(["2","wang","30"])
except Exception as e:
print("異常對象的類型是:%s"%type(e))
print("異常對象的内容是:%s"%e)
finally:
f.close()
xlrd子產品
xlrd子產品是用來處理 .xls 格式的文檔
打開.xls格式的文檔
import xlrd
data=xlrd.open_workbook('test.xls')
print(data)
##############################################
<xlrd.book.Book object at 0x000001BAC978E2B0>
擷取.xls文檔的列
import xlrd
data=xlrd.open_workbook('test.xls')
line=data.sheets()
print(line) #列印所有的列
print(line[1]) #列印第2列
可以看到有三列
#############################################################################
[<xlrd.sheet.Sheet object at 0x000001BACDE2EE10>, <xlrd.sheet.Sheet object at 0x000001BACDC55860>, <xlrd.sheet.Sheet object at 0x000001BACD7692E8>]
<xlrd.sheet.Sheet object at 0x000001BACDC55860>
檢視有多少行
import xlrd
data=xlrd.open_workbook('test.xls')
line=data.sheets()[0] #標明第一列
rows=line.nrows
print(rows)
##########################
984
列印第一行的資料
import xlrd
data=xlrd.open_workbook('test.xls')
line=data.sheets()[0]
print(line.row_values(0))
################################
['教工号', '機關', '姓名']
列印所有資料
import xlrd
data=xlrd.open_workbook('test.xls')
line=data.sheets()[0]
rows=line.nrows
for i in range(rows):
print(int(line.row_values(i)[0]))
将.xls格式的文檔轉換為 .txt格式的
import xlrd
datas=xlrd.open_workbook('test.xls')
allline=datas.sheets() #資料中的所有列數
lines=len(allline)
line=datas.sheets()[0] #標明第一列
rows=line.nrows #資料中的列數
print("這個文檔有%s列,有%s行"%(lines,rows))
try:
with open("test.txt","w",encoding='utf-8') as f:
for i in range(rows):
for j in range(lines):
data=line.row_values(i)[j]
f.write(str(data))
f.write(" ") #用空格隔開
f.write("\n") #每一行加換行符
except Exception as e:
print("異常對象的類型是:%s"%type(e))
print("異常對象的内容是:%s"%e)
finally:
f.close()