STUNUM

面有萌色,胸有丘壑。心有猛虎,细嗅蔷薇。

嗨,我是王鑫 (@stunum),一名 Python 开发者。


Python web开发,后端以Django框架为主,前端使用Vue.js...

python读取文件

python 读取文件常用的三种方式:.read().readline().readlines()

(一)read()方法:

一次性读取完整的文件,对大文件不太适合,容易内存爆炸。

file_object = open(filepath)
print(file_object.read())
file_object.close()

(二) readline()方法:

一行一行的读取文件,对内存占用比较好,每行末尾会有换行符输出。

file_object = open(filepath)
for i in file_object.readline():
    print(i)
file_object.close()

(三) readlines()方法:

自动将文件内容分析成一个行的列表。

file_object = open(filepath)
for i in file_object.readlines():
    print(i)
file_object.close()

以上三种方法都得在最后关闭文件(即 file_object.close()) 所以推荐另外一种方式:

with  open('files','r') as file_object:
    for line in file_object:
        print(line)

上面这个方法的好处在于不需要写关闭文件的方法,而且也不用去为了内存不够而担心,更大的优点是 不需要担心一些文件不存在/路径错误的异常出现。

最近的文章

检查网页编码

1、使用urllib模块的getparam方法:import urllib #import urllib.request (python3)urlBj = urllib.urlopen(‘http://www.baidu.com').info()print urlBj.getparam(‘charset’) #print(urlBj.getparam(‘charset’)) (python3)2、使用chardet模块:import chardetimport urlilb#imp...…

水滴石穿继续阅读
更早的文章

pip命令

pip使用实例1、安装pip install <名称>2、卸载pip uninstall <名称>3、查看待更新包pip list --outdate4、列出所有已安装的包pip list5、升级pip install --upgrade <名称>6、查看某个包的详情pip show --files <名称>pip的帮助Usage: pip <command> [options] Commands: install ...…

水滴石穿继续阅读