python3中,读取文件有三种方法:read()、readline()、readlines()。
这三种方法都支持接收变量以限制一次读取的数据量,但通常不使用该变量。
[En]
All three methods support receiving a variable to limit the amount of data read at a time, but it is not usually used.
本文旨在分析和总结上述三种阅读方法的用法和特点。
[En]
The purpose of this paper is to analyze and summarize the usage and characteristics of the above three reading methods.
- 功能:读取整个文件,并将文件内容放入一个字符串变量。
[En]
Features: read the entire file and put the contents of the file into a string variable.*
- 缺点:如果文件非常大,尤其是大于内存时,无法使用read()方法。
file = open('部门同事联系方式.txt', 'r') # 创建的这个文件,是一个可迭代对象try: text = file.read() # 结果为str类型 print(type(text)) #打印text的类型 print(text)finally: file.close() #关闭文件file"""李飞 177 70 13888888王超 170 50 13988888白净 167 48 13324434黄山 166 46 13828382"""
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()方法每次读取一行;返回的是一个字符串对象,保持当前行的内存
- 缺点:比readlines慢的多
file = open('部门同事联系方式.txt', 'r')
try:
while True:
text_line = file.readline()
if text_line:
print(type(text_line), text_line)
else:
break
finally:
file.close()
"""
李飞 177 70 13888888
王超 170 50 13988888
白净 167 48 13324434
黄山 166 46 13828382
"""
readline()读取整行,包括行结束符,并作为字符串返回
>>> file = open('兼职模特联系方式.txt', 'r')
>>> a = file.readline()
>>> a
'李飞 177 70 13888888\n'
特点:一次读取整个文件;自动将文件内容分析为几行
[En]
Features: read the entire file at once; automatically analyze the contents of the file into a list of lines
'''
学习中遇到问题没人解答?小编创建了一个Python学习交流群:711312441
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
file = open('部门同事联系方式.txt', 'r')
try:
text_lines = file.readlines()
print(type(text_lines), text_lines)
for line in text_lines:
print(type(line), line)
finally:
file.close()
"""
['李飞 177 70 13888888\n', '王超 170 50 13988888\n', '白净 167 48 13324434\n', '黄山 166 46 13828382']
李飞 177 70 13888888
王超 170 50 13988888
白净 167 48 13324434
黄山 166 46 13828382
"""
readlines()读取所有行,然后把它们作为一个字符串列表返回。
>>> file = open('兼职模特联系方式.txt', 'r')
>>> a = file.readlines()
>>> a
['李飞 177 70 13888888\n', '王超 170 50 13988888\n', '白净 167 48 13324434\n',
'黄山 166 46 13828382']
Original: https://www.cnblogs.com/djdjdj123/p/16444238.html
Author: Python探索牛
Title: Python教程:读取文件有三种方法:(read、readline、readlines)详细用法
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/499145/
转载文章受原作者版权保护。转载请注明原作者出处!