Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

File I/O in Python

1. Introduction

File Input/Output (I/O) in Python is a fundamental concept that allows you to read from and write to files on your system. This lesson covers the essential functions and methods for handling file I/O in Python.

2. Opening Files

In Python, you can open a file using the built-in open() function. The basic syntax is:

file = open('filename.txt', 'mode')

Modes:

  • 'r' - Read (default mode)
  • 'w' - Write (overwrites existing file)
  • 'a' - Append (adds to the end of the file)
  • 'b' - Binary mode (for non-text files)
  • 'x' - Exclusive creation (fails if the file exists)
Note: Always use the correct mode to avoid unintentional data loss.

3. Reading Files

To read the contents of a file, you can use the read(), readline(), or readlines() methods.

file = open('filename.txt', 'r')
content = file.read()
file.close()

You can also use a context manager to ensure the file is closed automatically:

with open('filename.txt', 'r') as file:
    content = file.read()

4. Writing Files

To write data to a file, you can use the write() or writelines() methods:

with open('filename.txt', 'w') as file:
    file.write("Hello, World!")
Tip: Using with ensures that the file is properly closed after its block is executed.

5. Closing Files

It is crucial to close files after their operations are complete to free up system resources. This can be done using the close() method, but using a context manager (as shown above) is preferred.

6. Best Practices

  • Always use a context manager when working with files.
  • Handle exceptions using try-except blocks.
  • Use relative paths when possible to enhance portability.
  • Ensure to use the correct file modes to avoid data loss.

7. FAQ

What is the difference between read() and readlines()?

The read() method reads the entire file contents as a single string, while readlines() reads the file line by line and returns a list of lines.

Can I read a binary file?

Yes, you can read binary files by opening them in binary mode, for example, open('file.bin', 'rb').

What happens if I try to write to a file that is opened in read mode?

Attempting to write to a file opened in read mode will raise an IOError.