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