python文件处理——文件读写
??hello!我是wakeyo_J,每天一个konwledge point,一起学python,让技术无限发散。
1. 读取文件
文件读取很简单,就三步。 
第一:在Windows的记事本中直接输入“愿你出走半生归来仍是少年!”  第二:通过代码读取文件
步骤:
- 使用open()函数打开文件。
myfile = open(r'test.txt','r')

-
myfile是变量,存放读取的文件。 -
第一个r是固定符号(原生字符)。 -
'test.txt’是需要读取文件的文件名,在这里, readfile.py文件与test.txt文件需要放在同一文件夹内。 -
最后一个‘r’是文件打开模式,‘r’代表read, 意为文件读取。 -
encoding=“utf-8”,编码采用utf-8。
- 读取文件中的内容。
myfilecontent = myfile.read()
print(myfilecontent)
使用read()函数,读取myfile变量中文件的数据,将数据放在myfilecontent变量中,之后使用print()函数,看看读取到什么内容。
- 最后一步,关闭文件。
myfile.close()
完整代码
myfile = open(r'test.txt','r',encoding="utf-8")
myfilecontent = myfile.read()
print(myfilecontent)
myfile.close()
效果: 
2. 写入文件
文件写入也是分三步。  首先,建立两个txt文本,在test1.txt文件与test2.txt文件中写入同样的文字内容 
进行文件写入操作
- 打开文件
myfile = open(r'test1.txt','w')
使用open()函数, 除了最后一个参数,其余参数不动, 把最后一个参数换成‘w’,是write意思,意为写入。
- 开始写入内容
myfile.write('从你的全世界路过')
- 关闭文件
myfile.close()
完整代码
myfile = open(r'test1.txt','w',encoding="utf-8")
myfile.write('从你的全世界路过')
myfile.close()
效果:   发现,原来的” 愿你出走半生归来仍是少年”内容已经消失。因为‘w’是写入模式,会直接清空test1.txt文件中的内容,重新写入。 如果你不想清空原来内容, 就要使用‘a’模式,意为追加。
追加写入代码
myfile = open(r'test2.txt','a',encoding="utf-8")
myfile.write('\n从你的全世界路过')
myfile.close()
效果:  
发现” 愿你出走半生归来仍是少年”内容还存在。
如果我们想写入的数据不是文本,而是图片怎么办?  可以看到里面还有‘wb’模式, 它的意思是以二进制的方式打开一个文件用于写入。图片、音频都是以二进制形式存在,所以使用wb模式就好了。
好多粗心的小伙伴,在打开文件,读写结束后,忘记关闭文件。但是不关闭文件就会占用电脑内存,使得电脑越来越慢,怎么解决呢?
with方法
with open(r'test.txt','a') as myfile:
myfile.write('你好')
print("写入完成")
效果: 
总结
??本文属于作者原创,转载请注明出处,不足之处,希望大家能过给予宝贵的意见,如有侵权,请私信。每天一个knowledge point,一起学python,让技术无限发散
|