python 读写函数
生活随笔
收集整理的這篇文章主要介紹了
python 读写函数
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1.open
使用open打開文件后一定要記得調(diào)用文件對象的close()方法。比如可以用try/finally語句來確保最后能關(guān)閉文件。
file_object = open('thefile.txt') try: all_the_text = file_object.read( ) finally: file_object.close( )2、讀文件
input = open('data', 'r') #第二個參數(shù)默認(rèn)為r input = open('data')讀二進制文件
input = open('data', 'rb')讀取所有內(nèi)容
''' 遇到問題沒人解答?小編創(chuàng)建了一個Python學(xué)習(xí)交流QQ群:778463939 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學(xué)習(xí)教程和PDF電子書! '''file_object = open('thefile.txt') try: all_the_text = file_object.read( ) finally: file_object.close( )讀固定字節(jié)
file_object = open('abinfile', 'rb') try: while True: chunk = file_object.read(100) if not chunk: break do_something_with(chunk) finally: file_object.close( )讀每行
list_of_all_the_lines = file_object.readlines( )如果文件是文本文件,還可以直接遍歷文件對象獲取每行:
for line in file_object:process line3.寫文件
寫文本文件
output = open('data', 'w')寫二進制文件
output = open('data', 'wb')追加寫文件
output = open('data', 'w+')寫數(shù)據(jù)
file_object = open('thefile.txt', 'w') file_object.write(all_the_text) file_object.close( )寫入多行
file_object.writelines(list_of_text_strings)注意,調(diào)用writelines寫入多行在性能上會比使用write一次性寫入要高
總結(jié)
以上是生活随笔為你收集整理的python 读写函数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 详解Django中Request对象的相
- 下一篇: 用Python获取Linux资源信息的三