Python文件操作

1.打开文件

2.对文件进行操作

3.关闭文件

f = open('路径','模式',encoding = '编码方式')

路径:

绝对路径

相对路径

模式:

r:只读

w:只写

r+:读写

w+;写读

a:追加

以bytes类型操作的读写,在模式后面加 b 

编码方式:

utf-8,gbk

在使用bytes类型操作读写时,注意编码和解码(encoding,decoding)

操作方法:

  read()

  read(2)

  readline()

  readlines()

  for 循环读取

  write()

常用方法:

  read readable readline readlines for 循环
  seek tell write writeable

关闭文件

  f.close()

另一种打开方式,以防忘记关闭:

with open() as f:

原文地址:https://www.cnblogs.com/2018-01-30/p/8386560.html