Python Tutorial : File Objects - Reading and Writing to Files

本文介绍了如何在Python中使用FileObjects进行文件操作,包括打开、读取(逐行、指定长度)、写入、复制文本和图片文件,以及使用不同的文件模式。
摘要由CSDN通过智能技术生成

File Objects

create a file called demo.txt in the same directory as my Python file. Then let’s see how we can open and read this file from within Python now.

OPEN FILES:

f = open('demo.txt', 'r')

print(f.name)

f.close()

Here ‘r’ just for reading, ‘w’ just for writing and ‘r+’ for reading and writing

Remember to close the file that you open.

with open('demo.txt','r') as f:
	pass

In this way, you don’t need to close the file.

READ FILES :

f.read()
with open('demo.txt','r') as f:
    f_contents = f.read()
    print(f_contents)
    #print out all of the contents of our file
with open('demo.txt','r') as f:
    f_contents = f.read(10)
    print(f_contents)
    #print out 10 characters of our file
f.readline()
with open('demo.txt','r') as f:
    f_contents = f.readlines()
    print(f_contents)
    #get the next line in our file
LOOP
with open('demo.txt','r') as f:
    for line in f:
        print(line, end=' ')
with open('demo.txt','r') as f:
    size_to_read = 5
    f_contents = f.read(size_to_read)
    while len(f_contents) > 0:
        print(f_contents, end='@')
        f_contents = f.read(size_to_read)
#divide the content with 'size_to_read'
f.tell()

return the postion in the file

f.seek(#int)

set position

WRITE FILES:

with open('demo2.txt','w') as f:
    pass

If this file didn’t exit, this will create it.
If this file already exited, this will overwrite it.

COPY TEXT
with open('demo.txt','r') as rf:
    with open('demo2.txt','w') as wf:
        for line in rf:
            wf.write(line)
COPY PICTURE
with open('1.jpg', 'rb') as rf:
    with open('2.jpg', 'wb') as wf:
        for line in rf:
            wf.write(line)

‘b’ for binary mode

with open('1.jpg', 'rb') as rf:
    with open('2.jpg', 'wb') as wf:
        chunk_size = 4096
        rf_chunk = rf.read(chunk_size)
        while len(rf_chunk) > 0:
            wf.write(rf_chunk)
            rf_chunk = rf.read(chunk_size)

for more information in docs.python.org

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值