Python文件的基本操作和访问模式

基本操作:

  1. 创建文件对象
  2. 读或者写(分清读写模式)
  3. 关闭对象
# r:如果文件不存在报错,不支持写入,表示只读
file = open('student.txt', 'r')
file.write('aaa')
file.close()

# w:如果文件不存在自动创建,执行写入操作,会覆盖原有的内容
file = open('student.txt', 'w')
file.write('aaa')
file.close()

# a:如果文件不存在自动创建,在原有内容上追加新内容
file = open('student.txt', 'a')
file.write('aaa')
file.close()

# 访问模式可以省略,默认r
file = open('student.txt')
file.close()

# r+文件不存在报错,可以读文件
file = open('student.txt', 'r+')
print(file.read())
file.close()

# w+没有文件创建文件,读取文件内容为空,并且原文件会为空,因为新内容空的覆盖原内容
file = open('student.txt', 'w+')
print(file.read())
file.close()


# a+没有文件创建文件,读取文件内容为空,文件指针在最后,所以读不到数据
file = open('student.txt', 'a+')
print(file.read())
file.close()

二进制访问模式类似

posted @ 2021-03-08 21:38  code-G  阅读(205)  评论(0编辑  收藏  举报