当前位置:   article > 正文

Python教程:读取文件有三种方法:(read、readline、readlines)详细用法_简述读文件的三种方式

简述读文件的三种方式

python3中,读取文件有三种方法:read()、readline()、readlines()。

此三种方法,均支持接收一个变量,用于限制每次读取的数据量,但是,通常不会使用。

本文的目的:分析、总结上述三种读取方式的使用方法及特点。

一、read方法

  • 特点:读取整个文件,将文件内容放到一个字符串变量中。

  • 缺点:如果文件非常大,尤其是大于内存时,无法使用read()方法。

  1. file = open('部门同事联系方式.txt', 'r') # 创建的这个文件,是一个可迭代对象
  2. try:
  3. text = file.read() # 结果为str类型
  4. print(type(text)) #打印text的类型
  5. print(text)
  6. finally:
  7. file.close() #关闭文件file
  8. """
  9. <class 'str'>
  10. 李飞 177 70 13888888
  11. 王超 170 50 13988888
  12. 白净 167 48 13324434
  13. 黄山 166 46 13828382
  14. """

read()直接读取字节到字符串中,包括了换行符

  1. >>> file = open('兼职模特联系方式.txt', 'r')
  2. >>> a = file.read()
  3. >>> a
  4. '李飞 177 70 13888888\n王超 170 50 13988888\n白净 167 48 13324434\n黄山 166 46 13828382'

二、readline方法

  • 特点:readline()方法每次读取一行;返回的是一个字符串对象,保持当前行的内存

  • 缺点:比readlines慢的多

  1. file = open('部门同事联系方式.txt', 'r')
  2. try:
  3. while True:
  4. text_line = file.readline()
  5. if text_line:
  6. print(type(text_line), text_line)
  7. else:
  8. break
  9. finally:
  10. file.close()
  11. """
  12. <class 'str'> 李飞 177 70 13888888
  13. <class 'str'> 王超 170 50 13988888
  14. <class 'str'> 白净 167 48 13324434
  15. <class 'str'> 黄山 166 46 13828382
  16. """

readline()读取整行,包括行结束符,并作为字符串返回

  1. >>> file = open('兼职模特联系方式.txt', 'r')
  2. >>> a = file.readline()
  3. >>> a
  4. '李飞 177 70 13888888\n'

三、readlines方法

特点:一次性读取整个文件;自动将文件内容分析成一个行的列表

  1. '''
  2. 学习中遇到问题没人解答?小编创建了一个Python学习交流群:711312441
  3. 寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
  4. '''
  5. file = open('部门同事联系方式.txt', 'r')
  6. try:
  7. text_lines = file.readlines()
  8. print(type(text_lines), text_lines)
  9. for line in text_lines:
  10. print(type(line), line)
  11. finally:
  12. file.close()
  13. """
  14. <class 'list'> ['李飞 177 70 13888888\n', '王超 170 50 13988888\n', '白净 167 48 13324434\n', '黄山 166 46 13828382']
  15. <class 'str'> 李飞 177 70 13888888
  16. <class 'str'> 王超 170 50 13988888
  17. <class 'str'> 白净 167 48 13324434
  18. <class 'str'> 黄山 166 46 13828382
  19. """

readlines()读取所有行,然后把它们作为一个字符串列表返回。

  1. >>> file = open('兼职模特联系方式.txt', 'r')
  2. >>> a = file.readlines()
  3. >>> a
  4. ['李飞 177 70 13888888\n', '王超 170 50 13988888\n', '白净 167 48 13324434\n',
  5. '黄山 166 46 13828382']

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/700845
推荐阅读
相关标签
  

闽ICP备14008679号