File Interactions#

File interaction in Python is an essential skill for developers because it allows you to read, write, and manipulate data stored in files on your computer. Understanding how to handle files not only enables you to process real-world data efficiently but also ensures data integrity and proper memory management.

Opening and Reading Files#

To interact with files in Python, you start by opening them. The primary method for opening a standard text file in Python is the open() method. The basic approach is to assign the result of open() to a variable, which creates a file object:

f = open("./my_sample_text_file.txt")
text = f.read()
f.close()

This code opens the file named my_sample_text_file.txt, reads its contents, assigns them to the text variable, and then explicitly closes the file using f.close(). After this, you can print the contents of the file to the standard output.

Using the with Keyword#

However, Python provides a more robust and safer way to handle files using the with keyword:

with open("./my_sample_text_file.txt") as file_object:
    my_text = file_object.read()
    
print(my_text)
My Sample Text File

This approach not only simplifies the code but also ensures that Python handles any exceptions that might occur and automatically closes the file. Even if an error occurs or if the programmer forgets to close the file, the with statement guarantees proper file closure and memory management.

File Modes#

When opening a file, you can specify a file mode, which determines the type of interaction you intend to perform. Common file modes include:

  • r (read): Opens the file for reading.

  • w (write): Opens the file for writing and overwrites it if it already exists.

  • a (append): Opens the file for writing but appends data to the end of the file.

For example, you can write a list of motorcycles to a file using the w mode:

motorcycles = ['kawasaki', 'honda', 'ducati', 'bmw', 'suzuki']

with open("motorcycles.txt", "w") as f:
    for motorcycle in motorcycles:
        print(motorcycle, file=f) # each entry on its own line
        f.write(motorcycle) # all entries together, no spaces or line breaks

Further Resources#

Socratica: Text Files in Python