python 流写入文件_python 文件流

open | write | read

>>> with open('demo.txt' , 'wt') as f: #以文本(wt)形式写入操作

... f.write("hello guohai")

12

>>> with open('demo.txt' , 'rt') as f: #以文本(rt)形式读取操作

... data = f.read()

>>> data

'hello guohai'

>>> with open('demo.txt' , 'at') as f: #以文本(at)形式追加操作

... f.write('hello zeopean')

13

>>> with open('demo.txt' , 'rt') as f:

... data = f.read()

>>> data

'hello guohaihello zeopean'

-- print 输出到文件中

with open('d:/work/test.txt', 'wt') as f:

print('Hello World!', file=f)

-- 二进制读写

如果你想从二进制模式的文件中读取或写入文本数据,必须确保要进行解码和编码

操作。比如:

1 with open('somefile.bin', 'rb') as f:2

3 data = f.read(16)4

5 text = data.decode('utf-8')6

7 with open('somefile.bin', 'wb') as f:8

9 text = 'Hello World'

10

11 f.write(text.encode('utf-8'))12

13

-- 判断文件是否存在

>>> importos>>> if not os.path.exists('somefile'):

... with open('somefile', 'wt') as f:

... f.write('Hello\n')

...else:

...print('File already exists!')

...

File already exists!

StringIO | BytesIO

1 --StringIO2

3 >>> s =io.StringIO()4

5 >>> s.write('Hello World\n')6

7 12

8

9 >>> print('This is a test', file=s)10

11 15

12

13 >>>s.getvalue()14

15 'Hello World\nThis is a test\n'

16

17 >>>

18

19 >>> s = io.StringIO('Hello\nWorld\n')20

21 >>> s.read(4)22

23 'Hell'

24

25 >>>s.read()26

27 'o\nWorld\n'

28

29 >>>

30

31

32

33 --BytesIO34

35 >>> s =io.BytesIO()36

37 >>> s.write(b'binary data')38

39 >>>s.getvalue()40

41 b'binary data'

42

43 >>>

readinto | bytearray | memoryview

1 record_size = 32

2

3 buf =bytearray(record_size)4

5 with open('somefile', 'rb') as f:6

7 whileTrue:8

9 n =f.readinto(buf)10

11 if n

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值