4

Python爬虫编程思想(74): 使用FileInput对象读取文件

 2 years ago
source link: https://blog.csdn.net/nokiaguy/article/details/121258628
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爬虫编程思想(74): 使用FileInput对象读取文件

        如果需要读取一个非常大的文件时,使用readlines函数会占用太多内存,因为该函数会一次性将文件所有的内容都读到列列表中,列表中的数据都需要放到内存中,所以非常占内存,为了解决这个问题,可以使用for循环和readline方法逐行读取,也可以使用fileinput模块中的input函数读取指定的文件。

        input方法返回一个FileInput对象,通过FileInput对象的相应方法可以对指定文件进行读取, FileInput对象使用的缓存机制,并不会一次性读取文件的所有内容,所以比readlines函数更节省内存资源。

        下面的例子使用fileinput.input方法读取了urls.txt文件,并通过for循环获取了每一行值,同时调用了fileinput.filename方法和fileinput.lineno方法分别获取了正在读取的文件名和当前的行号。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK