Note on Python File Operation

How to Read Files Piece by Piece

h = open('test.txt', 'r')
for line in h:
    print(h)
h.close()

# read the file in chunks (for binary mode)
h = open('test.txt', 'r')
while True:
    data = h.read(1024)
    print(data)
    if not data:
        break
h.close()

How to Read Binary File

h = open('test.pdf', 'rb')

How to Write Files

# `w` for write-mode, `wb` for write-binary-mode
h = open('test.txt', 'w')
h.write('ssdfsdf')
h.close()

'''
The file handle also has a `writelines` method that will accept a list of strings that the handle will write to disk in order.
'''

Using the with operator

The with operator creates what is known as context manager in PYthon that will automatically close the file for you when you are done with processing it.

with open('test.txt', 'r') as h:
    for line in h:
        print(line)

Once you leave the with block, the file handle will close and you won’t be able to use it any more.

Catching Errors

try:
    h = open('test.txt', 'r')
    for line in h:
        print(line)
except IOError:
    print('An IOError has occurred!')
finally:
    h.close()

Do the same thing using with

try:
    with open('test.txt', 'r') as h:
        for line in h:
            print(line)
    except IOError:
        print('An IOError has occurred!')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值