python:文件读写操作
#打開(kāi)文件
file = open(filename,‘rb’)
【打開(kāi)文件】
open() 函數(shù)
- 常用格式 :open(file, mode=‘r’)
https://docs.python.org/3/library/functions.html
這里有所有python內(nèi)建的函數(shù)及描述文檔
eg1:
上面的代碼以w(寫)的方式打開(kāi)文件d:/1.txt,然后寫入 hello python, 最后關(guān)閉文件。運(yùn)行程序后,找到d:/1.txt文件并打開(kāi),發(fā)現(xiàn)里面的內(nèi)容是 hello python, 說(shuō)明程序運(yùn)行成功
eg2:
f = open('d:/1.txt', 'r') msg = f.read() f.close() print(msg)運(yùn)行結(jié)果:
hello python
以 r (只讀)方式打開(kāi)文件,然后讀取文件內(nèi)容,再輸出文件內(nèi)容,即輸出前面寫入的 hello python
eg3:
打開(kāi)文件寫入多行內(nèi)容
運(yùn)行程序,顯示結(jié)果:
<class ‘list’>
hello python1
hello python2
hello python3
hello python4
hello python5
hello python6
hello python7
hello python8
hello python9
hello python10
可見(jiàn)readlines()方法返回一個(gè)list對(duì)象
eg4:
f = open("d:/2.txt", 'r') line = f.readline() while line:print(line.strip())line = f.readline() f.close()運(yùn)行程序,顯示結(jié)果:
hello python1
hello python2
hello python3
hello python4
hello python5
hello python6
hello python7
hello python8
hello python9
hello python10
readline()方法一次只讀取一行,
read()方法返回文件全部?jī)?nèi)容,readlines()方法以列表的形式返回文件全部?jī)?nèi)容
以 a 方式打開(kāi)文件,寫入的內(nèi)容將追加到最后。運(yùn)行上面的代碼發(fā)現(xiàn)確實(shí)追加了內(nèi)容到最后
關(guān)鍵字with 在不再需要訪問(wèn)文件后將其關(guān)閉, python會(huì)保證with代碼段內(nèi)的文件對(duì)象自動(dòng)關(guān)閉
with open("d:/3.txt", 'w') as f:f.write('寫入文件的內(nèi)容') #打開(kāi)excel文件 workbook = xlrd.open_workbook(filename)#獲取sheet sheet = workbook.sheet_by_name(sheetname)總結(jié)
以上是生活随笔為你收集整理的python:文件读写操作的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: python:数据操作小技巧
- 下一篇: stm32链接电脑提示无法识别的驱动设备