【Python基础知识】Python文件读写五大方法

发布 : python培训      来源:python干货资料

2020-08-05 18:29:42

Python读写文件时非常流行的操作。Python读文件有3种方法:read()、readline()和readlines()。Python写文件有2种方法:write()和writelines()。

可以先编辑一下文件并写入一些信息。在文本文件“example.txt”中写入如下内容:

  1. "Whenever you feel like criticizing anyone,"
  2. he told me,
  3. “just remember that all the people in this world
  4. haven’t had the advantages that you’ve had.

1、读取文件

文件对象的read()方法用于读取文件,当不传递任何参数时,read()方法将读取整个文件:

  1. >>> with open('example.txt', 'r') as f: # 使用r模式
  2. ... print(f.read()) # 将读取内容打印出来
  3. ...
  4. "Whenever you feel like criticizing anyone,"
  5. he told me,
  6. “just remember that all the people in this world
  7. haven’t had the advantages that you’ve had.

read()方法也可以通过传递参数来指定读取的字节数:

  1. >>> with open('example.txt', 'r') as f:
  2. ... print(f.read(8)) # 读取8个字节的数据
  3. ...
  4. "Wheneve

readline()方法用于读取整行文本:

  1. >>> with open('example.txt', 'r') as f:
  2. ... print(f.readline()) # 仅读取第一行
  3. ...
  4. "Whenever you feel like criticizing anyone,"
  5. >>> with open('example.txt', 'r') as f:
  6. ... for _ in range(3): # 读取前三行文本
  7. ... print(f.readline())
  8. ...
  9. "Whenever you feel like criticizing anyone,"
  10. he told me,
  11. “just remember that all the people in this world

readline()方法同样可以通过传递参数来指定读取的字节数:

  1. >>> with open('example.txt', 'r') as f:
  2. ... for _ in range(3):
  3. ... print(f.readline(6))
  4. ...
  5. "Whene
  6. ver yo
  7. u feel

readlines()方法用于读取文件对象剩余的全部行,以列表的形式返回:

  1. >>> with open('example.txt', 'r') as f:
  2. ... print(f.readlines())
  3. ...
  4. ['"Whenever you feel like criticizing anyone," \n', 'he told me, \n', '“just remember that all the people in this world \n', 'haven’t had the advantages that you’ve had.']
  5. >>> with open('example.txt', 'r') as f:
  6. ... print(f.readline()) # 先使用readline()读取一行
  7. ... print(f.readlines()) # 再使用readlines()读取剩余的全部行
  8. ...
  9. "Whenever you feel like criticizing anyone,"
  10. ['he told me, \n', '“just remember that all the people in this world \n', 'haven’t had the advantages that you’ve had.']

2、写入文件

使用Python写入文件时,需要以写“w”或附加“a”模式打开文件。需要谨慎使用“w”模式,因为它会覆盖文件(如果文件已存在),该文件之前的所有数据都将被删除。写入字符串或字节序列(对于二进制文件)是使用write()方法实现的,返回写入文件的字符数:

  1. >>> with open('example.txt', 'w') as f: # 使用'w'模式
  2. ... f.write('I love Python')
  3. ... f.write('Hello!')
  4. ...
  5. 13
  6. 6

打开文本文件“example.txt”,会发现文件中的内容已被覆盖了,原先的所有数据都被删除了,此时文件中的内容是刚刚使用write()方法写入的。

writelines()方法用于一次性写入多行文件:

  1. >>> with open('example.txt', 'a') as f: # 使用'a'追加模式
  2. ... f.writelines(['Over and Over', 'DealBreaker'])
  3. ...

再次打开文本文件“example.txt”,会发现文件中原先的数据没有被删除,使用write()方法写入的数据被追加到了原数据的末尾。

THE END  

声明:本站稿件版权均属中公教育优就业所有,未经许可不得擅自转载。

领取零基础自学IT资源

涉及方向有Java、Web前端、UI设计、软件测试、python等科目,内容包含学习路线、视频、源码等

点击申请领取资料

点击查看资料详情 

收起 


 相关推荐

问题解答专区
返回顶部