reading-notes

View on GitHub

Reading and Writing Files

What Is a File?

At its core, a file is a contiguous set of bytes used to store data. This data is organized in a specific format and can be anything as simple as a text file or as complicated as a program executable. In the end, these byte files are then translated into binary 1 and 0 for easier processing by the computer.

Files on most modern file systems are composed of three main parts:

Opening and Closing a File in Python

When you want to work with a file, the first thing to do is to open it. This is done by invoking the open() built-in function. open() has a single required argument that is the path to the file.

When you’re manipulating a file, there are two ways that you can use to ensure that a file is closed properly, even when encountering an error:

1- try-finally block:

reader = open('dog_breeds.txt')
try:
    # Further file processing goes here
finally:
    reader.close()

2- with statement:An alternative way of doing this is using with statements. This creates a temporary variable (often called f), which is only accessible in the indented block of the with statement.

with open("filename.txt") as f:
   print(f.read())

You can specify the mode used to open a file by applying a second argument to the open function.

Reading and Writing Opened Files

There are multiple methods that can be called on a file object to help you out:

As with reading files, file objects have multiple methods that are useful for writing to a file: