Published on

Simplifying File I/O in Python with `with - as`

Authors
  • avatar
    Name
    hwahyeon
    Twitter

File Reading Code in General Languages:

In general programming languages, reading a file typically involves repeatedly reading until EOF (End of File) is reached.

f = open('myfile.txt', 'r')
while True:
    line = f.readline()
    if not line:
        break
    raw = line.split()
    print(raw)
f.close()

In this code, the open() function is used to open the file, and readline() reads each line one by one. EOF is checked to stop reading, and f.close() is called at the end to close the file.

Using with - as in Python

In Python, the with - as statement allows for simpler file reading.

with open('myfile.txt') as file:
    for line in file.readlines():
        print(line.strip().split('\t'))

Advantages:

  • Automatic File Closing: When the with - as block ends, the file is automatically closed, so there is no need to call f.close().
  • No Need to Check EOF: The readlines() method reads until EOF, so there's no need to check for EOF inside a while loop.

Additional Information

The with - as statement can be used not only for files but also for other resources such as sockets and http. This syntax helps prevent resource leaks by automatically handling resource cleanup.

import socket

# TCP client example
with socket.create_connection(('example.com', 80)) as sock:
    sock.sendall(b'GET / HTTP/1.1\r\nHost: example.com\r\n\r\n')
    response = sock.recv(4096)
    print(response.decode('utf-8'))
  • sock.sendall() sends an HTTP GET request, and sock.recv() receives the response.
  • The with - as statement ensures that the socket created by socket.create_connection() is automatically closed when the with block ends.