打开文件

  1. # 文件路径可以是绝对路径也可以是相对路径
  2. f = open('data.txt') # 打开文件,默认以只读模式 ("r") 打开
  3. # 打开文件,默认以写入模式 ("w") 打开
  4. f = open('data.txt', "w")
  5. # 指定编码类型
  6. f = open('scores.txt', encoding='gbk')
  7. f.close() # 关闭文件,释放资源

读文件

  1. f = open('data.txt') # 打开文件,默认以只读模式 ("r") 打开
  2. data = f.read() # 读取文件
  3. print (data) # 输出读取到的文件内容
  4. f.close() # 关闭文件,释放资源
  5. # 其他 API
  6. readline() #读取一行内容
  7. readlines() #把内容按行读取至一个list中

写文件

  1. data = 'I will be in a file.\nSo cool!'
  2. out = open('output.txt', 'w') # 打开文件,以写入模式 ("w") 打开
  3. out.write(data)
  4. out.close()