web-profile

Python contextlib (Working with files - open, read, write, copy, binary)

Working with files using context manager:

# Working with context manager directly
with open('data.txt', 'w') as f:
    f.write('Test')
    # no need to write f.close()
    # because it will be handled by python automatically

print(f.closed) # True (because file was closed automatically)


# Working with context manager using a class
class Open_File():

    def __init__(self, filename, mode):
        self.filename = filename
        self.mode = mode

    def __enter__(self):
        self.file = open(self.filename, self.mode)
        return self.file

    def __exit__(self, exc_type, exc_val, traceback):
        self.file.close()

with Open_File('data_2.txt', 'w') as f2:
    f2.write('Test 2')

print(f2.closed) # True (because file was closed by __exit__)


# Working with context manager using a function
from contextlib import contextmanager

@contextmanager
def open_file(file, mode):
    try:
        f = open(file, mode)
        yield f
    finally:
        f.close()


with open_file('data_3.txt', 'w') as f3:
    f3.write('Test 3.')

print(f3.closed) # True

Example to get the list of files in the directory with context manager:

import os
from contextlib import contextmanager

@contextmanager
def dir_filelist(destination):
    try:
        cwd = os.getcwd()
        os.chdir(destination)
        yield
    finally:
        os.chdir(cwd)

with dir_filelist('folder_1'):
    print(os.listdir()) # ['data.txt', 'data_2.txt', 'data_3.txt']


with dir_filelist('folder_2/subfolder'):
    print(os.listdir()) # ['data_q2.txt', 'data_q3.txt', 'data_qq.txt']

Working with files (open, read, write, copy, binary)

# 'r' - read mode
# 'w' - write mode (override mode) (creates new file, if it doesn't exist)
# 'r+' - read and write mode
# 'a' - append mode (add mode) (creates new file, if it doesn't exist)
# 'b' - binary mode

# open file for reading with context manager
with open('data.txt', 'r') as f:
    # print(dir(f)) # prints all the available attributes and methods for the object
    print(f.name) # 'data.txt'
    print(f.mode) # r
    print(f.closed) # False
    print(f.readable()) # True
    print(f.writable()) # False
    # f_contents = f.read() # read all lines from file
    # print(f_contents) # Test /n Test 2 /n Test 3
    # fl = f.readlines() # keep all lines if you need to reuse them
    for line in f: # iterator will be emptied after the first run
        print(line) # Test; Test 2; Test 3

# no need for f.close()
# file will be closed automatically with context manager
print(f.closed) # True


# open file for writing with context manager
with open('data-write.txt', 'w') as f:
    f.write('Test 1')
    f.write('Test 2')

# copy text file content into another file with context manager
with open('data.txt', 'r') as rf:
    with open('data-copy.txt', 'w') as wf:
        for line in rf:
            wf.write(line)

# copy binary file content into another file with context manager
with open('video.mp4', 'rb') as rf2:
    with open('video-copy.mp4', 'wb') as wf2:
        for line in rf2:
            wf2.write(line)

# copy binary file chunk by chunk into another file with context manager
with open('video2.mp4', 'rb') as rf3:
    with open('video2-copy.mp4', 'wb') as wf3:
        chunk_size = 4096
        rf_chunk = rf3.read(chunk_size)
        while len(rf_chunk) > 0:
            wf3.write(rf_chunk)
            rf_chunk = rf3.read(chunk_size)

Leave a Reply

Your email address will not be published.