2

Python爬虫编程思想(73): 读行和写行

 2 years ago
source link: https://blog.csdn.net/nokiaguy/article/details/121258547
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爬虫编程思想(73): 读行和写行

        读写一整行是纯文本文件最常用的操作,尽管可以使用read和write方法加上行结束符来读写文件中的整行,但比较麻烦。因此,如果要读写一行或多行文本,建议使用readline方法、readlines方法和writelines方法。注意,并没有writeline方法,写一行文本需要直接使用write方法。

        readline方法用于从文件指针当前位置读取一整行文本,也就是说,遇到行结束符停止读取文本,但读取的内容包括了行结束符。readlines方法从文件指针当前的位置读取后面所有的数据,并将这些数据按行结束符分隔后,放到列表中返回。writelines方法需要通过参数指定一个字符串类型的列表,该方法会将列表中的每一个元素值作为单独的一行写入文件。

        下面的例子通过readline方法、readlines方法和writelines方法对urls.txt文件进行读写行操作,并将读文件后的结果输出到控制台。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK