前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 文件读写和编码

python 文件读写和编码

作者头像
用户5760343
发布2019-09-29 20:23:31
5400
发布2019-09-29 20:23:31
举报
文章被收录于专栏:sktjsktj

Read the entire file as a single string

with open('somefile.txt', 'rt') as f: data = f.read()

Iterate over the lines of the file

with open('somefile.txt', 'rt') as f: for line in f: # process line ...

Write chunks of text data

with open('somefile.txt', 'wt') as f: f.write(text1) f.write(text2) ...

Redirected print statement

with open('somefile.txt', 'wt') as f: print(line1, file=f) print(line2, file=f) ...

代编码

with open('somefile.txt', 'rt', encoding='latin-1') as f:

newline

with open('somefile.txt', 'rt', newline='') as f:

errors

Replace bad chars with Unicode U+fffd replacement char f = open('sample.txt', 'rt', encoding='ascii', errors='replace') f.read() 'Spicy Jalape?o!' Ignore bad chars entirely g = open('sample.txt', 'rt', encoding='ascii', errors='ignore') g.read() 'Spicy Jalapeo!'

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.09.29 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Read the entire file as a single string
  • Iterate over the lines of the file
  • Write chunks of text data
  • Redirected print statement
  • 代编码
  • newline
  • errors
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档