Note on Python File Operation

本文介绍了如何使用Python逐块读取文本文件和二进制文件的方法,并演示了如何进行文件的写入操作。此外,还展示了如何利用with语句来确保文件在使用完毕后能够正确关闭,以及如何捕获错误来处理文件读取过程中可能出现的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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、付费专栏及课程。

余额充值