Python读写文件基础知识点

时间:2022-08-25 13:40:50

在 python 中,读写文件有 3 个步骤:

 1.调用 open()函数,返回一个 file 对象。

 2.调用 file 对象的 read()或 write()方法。 

 3.调用 file 对象的 close()方法,关闭该文件。

新建一个sj.txt文档,内容为hello.

输入代码:

?
1
hellofile=open('f:\\sj.txt')

 

调用open将返回一个file对象。file对象代表计算机中的一个文件,它只是python中另一种类型的值。

Python读写文件基础知识点

有了file对象,就可以开始从它读取内容。希望读取整个文件就用read(),读取用readlines()

Python读写文件基础知识点

如果要写文件,就要改变下open函数的默认参数

?
1
hl=open('f:\\sj.txt','w')

 

Python读写文件基础知识点