1、读取,read()方法返回文件中保存的字符串。
readlines()方法,从文件中获取字符串列表。列表中的每个字符串是文本中的每一行。
>>>helloContent=file.read() >>>helloContent 'Helloworld!'
2、写入,把w作为第二个参数传递给open(),在写作模式下打开文件,就可以通过write()的方式将内容写入文件。
w模式将删除文件的原始内容并重写。
如果不想删除原始内容,可以通过a模式将内容添加到文件中。
>>>baconFile=open('bacon.txt','w') >>>baconFile.write('Helloworld!\n') 13 >>>baconFile.close() >>>baconFile=open('bacon.txt','a') >>>baconFile.write('Baconisnotavegetable.') 25 >>>baconFile.close() >>>baconFile=open('bacon.txt') >>>content=baconFile.read() >>>baconFile.close() >>>print(content) Helloworld! Baconisnotavegetable.
以上就是python文件读取和写入的方法,希望对大家有所帮助。
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。