700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > unity webgl读写txt文件_python Files文件读写操作

unity webgl读写txt文件_python Files文件读写操作

时间:2020-09-20 10:50:38

相关推荐

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记

下面的是我的公众号二维码图片,欢迎关注。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。