目录
- 一、read方法
- 二、readline方法
- 三、readlines方法
正文
python3中,读取文件有三种方法:read()、readline()、readlines()。
此三种方法,均支持接收一个变量,用于限制每次读取的数据量,但是,通常不会使用。
本文的目的:分析、总结上述三种读取方式的使用方法及特点。
一、read方法
特点:读取整个文件,将文件内容放到一个字符串变量中。
缺点:如果文件非常大,尤其是大于内存时,无法使用read()方法。
1 file = open('部门同事联系方式.txt', 'r') # 创建的这个文件,是一个可迭代对象 2 3 try: 4 text = file.read() # 结果为str类型 5 print(type(text)) #打印text的类型 6 print(text) 7 finally: 8 file.close() #关闭文件file 9 """ 10 <class 'str'> 11 李飞 177 70 13888888 12 王超 170 50 13988888 13 白净 167 48 13324434 14 黄山 166 46 13828382 15 """
read()直接读取字节到字符串中,包括了换行符
>>> file = open('兼职模特联系方式.txt', 'r') >>> a = file.read() >>> a '李飞 177 70 13888888\n王超 170 50 13988888\n白净 167 48 13324434\n黄山 166 46 13828382'
二、readline方法
特点:readline()方法每次读取一行;返回的是一个字符串对象,保持当前行的内存
缺点:比readlines慢的多
1 file = open('部门同事联系方式.txt', 'r') 2 3 try: 4 while True: 5 text_line = file.readline() 6 if text_line: 7 print(type(text_line), text_line) 8 else: 9 break 10 finally: 11 file.close() 12 """ 13 <class 'str'> 李飞 177 70 13888888 14 15 <class 'str'> 王超 170 50 13988888 16 17 <class 'str'> 白净 167 48 13324434 18 19 <class 'str'> 黄山 166 46 13828382 20 """
readline()读取整行,包括行结束符,并作为字符串返回
>>> file = open('兼职模特联系方式.txt', 'r') >>> a = file.readline() >>> a '李飞 177 70 13888888\n'
三、readlines方法
特点:一次性读取整个文件;自动将文件内容分析成一个行的列表
1 file = open('部门同事联系方式.txt', 'r') 2 3 try: 4 text_lines = file.readlines() 5 print(type(text_lines), text_lines) 6 for line in text_lines: 7 print(type(line), line) 8 finally: 9 file.close() 10 """ 11 <class 'list'> ['李飞 177 70 13888888\n', '王超 170 50 13988888\n',
'白净 167 48 13324434\n', '黄山 166 46 13828382'] 12 <class 'str'> 李飞 177 70 13888888 13 14 <class 'str'> 王超 170 50 13988888 15 16 <class 'str'> 白净 167 48 13324434 17 18 <class 'str'> 黄山 166 46 13828382 19 """
readlines()读取所有行,然后把它们作为一个字符串列表返回。
>>> file = open('兼职模特联系方式.txt', 'r') >>> a = file.readlines() >>> a ['李飞 177 70 13888888\n', '王超 170 50 13988888\n', '白净 167 48 13324434\n',
'黄山 166 46 13828382']