unity webgl读写txt文件_python Files文件读写操作
生活随笔
收集整理的這篇文章主要介紹了
unity webgl读写txt文件_python Files文件读写操作
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
今天學習python的Files文件讀寫操作,并記錄學習過程歡迎大家一起交流分享。
首先新建一個文本文件test.txt,內容如下:
hello worldhello youhello mehello pythonhello universe然后新建一個python文件命名為py3_file.py,在這個文件中進行操作代碼編寫:
#文件讀寫操作#打開一個文件test.txt#文件常見打開模式#r:讀文件#w:寫文件#a:追加文件#####讀取文件操作#####f = open('test.txt','r')#打印文件名print(f.name)#test.txt#打印文件打開的模式print(f.mode)#r#關閉文件f.close()#使用with打開文件#好處是不用關心文件是否關閉#當我們退出with代碼塊后#會自動關閉文件with open('test.txt','r') as rf: pass#驗證文件是否已經關閉print(rf.closed)#True#試著在with代碼塊外執行讀取數據#print(rf.read())#出現異常 文件已經關閉了# ValueError: I/O operation on closed file.#讀取文件內容with open('test.txt','r') as rf_obj: contents = rf_obj.read() print (contents)#注意:當test.txt文件內容很少的時候# 上邊的代碼沒什么問題#如果是一個非常大的文本文件#直接去read()到內存中 會吃不消#甚至出現打不開的情況#改良如下使用readlines代替read#一行一行讀取,直到全部讀取完畢with open('test.txt','r') as rf_obj: contents = rf_obj.readlines() print (contents)#運行得到的結果是一個list#包含文件中的每一行內容#這種方式顯而易見對于很大的文件來說#也是不合理的#接下來繼續改良#使用readline()代替readlines()#每次讀取一行with open('test.txt','r') as rf_obj: contents = rf_obj.readline() print(contents,end='')#運行得到文本文件中的第一行數據#這種方式讀取數據需要寫很多次readline()#這里我們繼續改良#使用for循環迭代 替代readline()、readlines()with open('test.txt','r') as rf_obj: for line in rf_obj: print(line,end='')print ()#這種方式不會一次讀取所有內容到內存中#一行一行的讀取,就不比擔心內存問題#改良版的read(size)應對大文件讀取with open('test.txt','r') as rf_obj: size_to_read = 10#定義每次讀取的大小 contents = rf_obj.read(size_to_read) #rf_obj.tell()查看每次讀取的大小 #rf_obj.seek(0)尋址操作,從0的位置在開始讀 while(len(contents)>0): print(contents, end = '*') contents = rf_obj.read(size_to_read)#####寫入文件操作#####with open('test.txt','w') as wf: wf.write('Hello EveryOne')#使用w的寫入模式要注意會清空原有文件中的#所有內容,寫入新的內容#所以根據自己的需求這里要注意是使用w還是a#接下來看seek操作with open('test.txt','w') as wf: wf.write('Test') wf.seek(0) wf.write('R')#以上代碼釋義:#先將Test寫入test.txt文件中#然后文件尋址到開始位置索引0的地方#這里是T#然后將R寫入第0個位置#最終文件的內容為:Rest###接下來做一個文件的拷貝功能######流程為先讀取一個文件,將內容寫入一個新#創建的文件中with open('test.txt','r') as rf: with open('test_copy.txt', 'w') as wf: for line in rf: wf.write(line)#圖片的拷貝操作#這里注意圖片內容為字節類型#所以這里文件打開模式需要調整with open('r1000.jpg','rb') as rf: with open('r1000_copy.jpg', 'wb') as wf: chunk_size = 4096 rf_chunk = rf.read(chunk_size) while len(rf_chunk) > 0: wf.write(rf_chunk) rf_chunk = rf.read(chunk_size)運行結果:
test.txtrTruehello worldhello youhello mehello pythonhello universe['hello world', 'hello you', 'hello me', 'hello python', 'hello universe']hello worldhello worldhello youhello mehello pythonhello universehello worl*dhello yo*uhello me*hello pyt*honhello *universe*今天初學python的 Files文件讀寫操作學習就到這里!
關注公號yale記
下面的是我的公眾號二維碼圖片,歡迎關注。
總結
以上是生活随笔為你收集整理的unity webgl读写txt文件_python Files文件读写操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: hibernate框架 最新_java框
- 下一篇: 金牛座和十二星座配对(金牛和什么星座最配