2

Python爬虫编程思想(72): 读文件和写文件

 2 years ago
source link: https://blog.csdn.net/nokiaguy/article/details/121258492
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Python爬虫编程思想(72): 读文件和写文件

        使用open函数成功打开文件后,会返回一个TextIOWrapper对象,然后就可以调用该对象中的方法对文件进行操作了,TextIOWrapper对象有如下4个非常常用的方法。

  1. write(string):向文件写入内容,该方法返回写入文件的字节数。
  2. read([n]):读取文件的内容,n是一个整数,表示从文件指针指定的位置开始读取的n个字节。如果不指定n,该方法就会读取从当前位置往后的所有的字节。该方法返回读取的数据。
  3. seek(n):重新设置文件指针,也就是改变文件的当前位置。使用write方法向文件写入内容后,需要调用seek(0)才能读取刚才写入的内容。
  4. close():关闭文件,对文件进行读写操作后,关闭文件是一个好习惯。

        下面的例子分别使用'r'、'w'、'r+'、'w+'等文件模式打开文件,并读写文件的内容,读


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK