Python 读写文本文件方式

读写文本文件内容

输入也可以从文件中读取。 可以使用内置函数 open 打开文件。 使用 with 作为 语法(称为“上下文管理器”)使使用 open 和获取文件句柄变得超级容易:

with open('somefile.txt', 'r') as fileobj:
    # write code here using fileobj

这确保了当代码执行离开块时,文件会自动关闭。文件可以以不同的模式打开。 在上面的示例中,文件以只读方式打开。 打开现有的只读文件使用 r, Read。 如果您想将该文件作为字节读取,请使用 rb。 要将数据附加到现有文件,使用 a, 利用w 创建文件或覆盖任何现有的同名文件。 您可以使用 r+ 打开一个文件进行读和写。 open() 的第一个参数是文件名,第二个是模式。 如果模式留空,它将默认为只读r.

如创建一个文件,写:

with open('sample.txt', 'w')as fw:
    fw .write("line1\\nline2\\nline3")

文件被创建成功,内容分3行:

line1
line2
line3

读取文本文件内容,读:

with open('sample.txt', 'r')as fr:
    lines = fr.readlines()
    print(lines)

一次性读取所有行内容

输出:[‘line1\n’, ‘line2\n’, ‘line3’]

按行读取

with open('sample.txt', 'r')as fr:
    line = fr.readline()
    print(line, end='')
    while line:
        line = fr.readline()
        print(line,end='')

输出:
line1
line2
line3

简单的读取内容方式:

with open('sample.txt', 'r')as fr:
for f   in fr:
    print(f, end='')

输出:
line1
line2
line3

读取的是字符串还是字节形式:

with open('sample.txt', 'r')as fr:
    print(type(fr.read()))

输出:<class ‘str’>

with open('sample.txt', 'rb')as fr:
    print(type(fr.read()))

输出:<class ‘bytes’>

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

flysh05

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值