🐍 Python Q44 / 170

How to read and write files in Python?

AI-Powered Answer ✓ Answered

File I/O (Input/Output) is a fundamental operation in many programming tasks, allowing programs to interact with data stored persistently on a disk. Python provides straightforward and powerful ways to handle file operations, including reading from existing files and writing new data to files.

Opening a File

Before you can read from or write to a file, you must open it. Python's built-in open() function is used for this purpose. It returns a file object, which is then used to perform read or write operations.

The basic syntax is open(filename, mode). The filename is a string representing the path to the file. The mode is an optional string that specifies how the file is to be opened (e.g., read, write, append, binary, text). The default mode is 'r' (read).

python
# Open a file in read mode ('r')
file_read = open('my_document.txt', 'r')

# Open a file in write mode ('w') - creates new file or overwrites existing
file_write = open('new_data.txt', 'w')

# Open a file in append mode ('a') - creates new file or appends to existing
file_append = open('log.txt', 'a')

Reading Files

Once a file is open in read mode, you can use several methods on the file object to retrieve its content:

  • read(): Reads the entire content of the file as a single string.
  • readline(): Reads one line at a time from the file.
  • readlines(): Reads all lines of the file into a list of strings, where each string is a line.
python
# Assuming 'my_document.txt' exists with some content
file = open('my_document.txt', 'r')
content = file.read()
print("Entire file content:\n", content)
file.close() # Always close the file!
python
file = open('my_document.txt', 'r')
print("\nReading line by line:")
for line in file: # Iterate over file object directly for efficient line-by-line reading
    print(line.strip()) # .strip() removes trailing newline characters
file.close()

Writing Files

To write data to a file, open it in write ('w') or append ('a') mode. The primary methods for writing are:

  • write(string): Writes a string to the file. It does not add a newline character automatically.
  • writelines(list_of_strings): Writes a list of strings to the file. Each string in the list should end with a newline character if desired.
python
file = open('output.txt', 'w') # 'w' will create or overwrite
file.write("Hello, Python file handling!\n")
file.write("This is the second line.\n")
file.close()

file = open('output.txt', 'a') # 'a' will append
file.write("This line is appended.\n")
file.close()

Using `with` Statement (Recommended)

It is crucial to close files after you are done with them to free up system resources and ensure all changes are saved. Forgetting to close a file can lead to resource leaks or data corruption. Python's with statement (context manager) is the recommended way to handle files, as it automatically ensures the file is closed, even if errors occur.

python
# Example of reading with 'with'
try:
    with open('my_document.txt', 'r') as file:
        content = file.read()
        print("\nContent using 'with':\n", content)
except FileNotFoundError:
    print("my_document.txt not found. Please create it first.")
python
# Example of writing with 'with'
with open('output_with.txt', 'w') as file:
    file.write("This was written using the 'with' statement.\n")
    file.write("It's much safer!")

Different File Modes

ModeDescription
'r'Read (default). Opens a file for reading. Error if the file does not exist.
'w'Write. Opens a file for writing. Creates the file if it does not exist, or truncates (empties) the file if it exists.
'a'Append. Opens a file for appending. Creates the file if it does not exist. The file pointer is at the end of the file if it exists.
'r+'Read and Write. Opens a file for both reading and writing. The file pointer is at the beginning of the file.
'w+'Write and Read. Opens a file for both writing and reading. Creates the file if it does not exist, or truncates the file if it exists.
'a+'Append and Read. Opens a file for both appending and reading. The file pointer is at the end of the file.
'x'Exclusive Creation. Creates a new file and opens it for writing. Raises an error if the file already exists.
't'Text mode (default). Opens in text mode. Data is read/written as strings.
'b'Binary mode. Opens in binary mode. Data is read/written as bytes. Useful for images, executables, etc.