文件操作的時(shí)候
1.打開文件,使用open(),賦值給一個(gè)變量名;即取得句柄(對(duì)象)
2.通過文件句柄(對(duì)象)執(zhí)行命令
3.保存并關(guān)閉文件,使用close()
一、讀操作
1.打開文件
變量名=open('文件路徑','打開方式',encoding='字符編碼')
打開方式有兩種:
1.文本
‘r’ 只讀,【默認(rèn)】
‘w’寫文件【不可讀;不存在則創(chuàng)建;存在則清空原來的內(nèi)容再寫新內(nèi)容;】,
‘a(chǎn)’追加模式【不可讀;不存在則創(chuàng)建;存在則以追加的方式寫入新的內(nèi)容;】
2.字節(jié)(二進(jìn)制文件)
(b 表示以字節(jié)的方式操作,不需要編碼的參數(shù) encoding)
rb 字節(jié)方式讀取
wb 字節(jié)方式寫入,清空原文件內(nèi)容
ab 字節(jié)方式的追加寫入字符編碼就是解釋文本的方法,python在 windows 下是 gbk,在 linux 下是 utf-8,與文本不同的編碼打開方式會(huì)造成亂碼
2.對(duì)句柄(對(duì)象)進(jìn)行操作
data = f_obj.read() #把每行的數(shù)據(jù)賦給變量名data
print(data)
3.關(guān)閉文件用close()
實(shí)際操作的例子
f_obj = open('./a.txt', 'r') ##文件里面有who\n are\n you\n !\n
>-------------------------------
# 讀全部
content = f_obj.read()
print(content)
who
are
you
!
f_objf.seek(0)
#是按照光標(biāo)來操作的,經(jīng)過上一次的操作現(xiàn)在光標(biāo)移動(dòng)到了最后一行,繼續(xù)read則會(huì)無內(nèi)容;
因此要移動(dòng)光標(biāo)到第一行
# 每次讀一行
line1 = f_obj.readline() #只會(huì)輸入一行的內(nèi)容
line2 = f_obj.readline()
line3 = f_obj.readline()
line_list = f_obj.readlines() # 一次讀完,把每一行的內(nèi)容放在列表中,成為列表中的一個(gè)元素;readlines
二、寫操作
[root@localhost ~]# cat a.txt
name
shark
[root@localhost ~]# python3 #進(jìn)入python3
Python 3.7.6 (default, Dec 25 2019, 19:34:47)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>----------------------------------------------
寫普通文件
>>> f =open('a.txt','w',encoding="utf-8") #其實(shí)在打開的一瞬間就會(huì)清空里面的內(nèi)容
>>> for i in ["who","age"]:
... f.write("{}\n".format(i)) #這個(gè)是格式化輸出層的內(nèi)容
...
4 #這個(gè)數(shù)輸入的字符數(shù)
4
>>> exit()
[root@localhost ~]# cat a.txt
who
age
>---------------------------------------------
寫bytes文件
f_obj=open("hao\n",encoding='utf=8')
b1 = bytes('洋洋\n', encoding='utf-8')
b2 = '楊哥\n'.encode('utf-8')
#定義bytes內(nèi)容
f_obj.writelines([b1, b2]) #多行同時(shí)寫入
f_obj.close()
可以用for來找語句呀,這樣很方便。
>>> file_name = './a.txt'
>>> f_obj = open(file_name, 'r')
>>> for line in f_obj:
... print(line)
其他的方法
f.name # 文件名
f.closed # 文件是否關(guān)閉
f.readable() # 文件是否可讀
f.writable() # 文件是否可寫
f.flush() # 立刻將文件內(nèi)容從內(nèi)存刷到硬盤
例子:
with open("./python_learning/file.db",'r',encoding="utf-8") as f:
contend =f.read()
file_li=contend.split('-')
for line in file_li:
line = line.replace('=',': ').replace(';','\n')
file_name=line.split(': ')[1]
file_name1=file_name.split('\n')[0]
with open("{}.yaml".format(file_name1),'w') as wor: wor.write(line)
with (打開方式)... as ...:
pass
python2如果要打開文件要導(dǎo)入
import io
io.open()