Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Working with Different File Modes | Advanced File Handling & Context Managers
Python Structural Programming

Working with Different File Modes

Свайпніть щоб показати меню

Learn how to use different file modes in Python for reading, writing, and appending files with practical examples.

Python file modes include: 'r' for reading, 'w' for writing (creates/truncates), 'a' for appending (creates if missing), 'b' for binary mode, and '+' for read/write. Choose the right mode to avoid data loss.

Read Mode

The read mode ('r') opens an existing file for reading only. You cannot write or modify the file when using this mode. If the file does not exist, Python will raise a FileNotFoundError. Use this mode when you want to access and read data from a file without making any changes to its contents.

123456
with open("sample.txt", "w") as f: f.write("This is a sample file.\nSecond line.") with open("sample.txt", "r") as f: content = f.read() print(content)

This code creates a text file with sample content and then reads and prints the content from the file.

Write Mode

The write mode (w) in Python opens a file for writing. Use w mode when you want to start fresh with a file, either by creating a new one or by clearing out an existing file to replace its contents. Be careful: any existing data in the file will be lost when you open it with w mode.

1234567891011
with open("write_example.txt", "w") as file: file.write("This file was created or overwritten using write mode.\n") with open("write_example.txt", "r") as file: print(file.read()) with open("write_example.txt", "w") as file: file.write("Every time you run this code, the contents are replaced.\n") with open("write_example.txt", "r") as file: print(file.read())

This code shows the file content after the first write and then after overwriting, so you can see how previous data is erased and replaced with new content.

Append Mode

Append mode, specified by the file mode 'a', opens a file for writing by adding new content to the end of the file. If the file does not exist, it will be created automatically. This mode is useful when you want to preserve existing data and simply add more information at the end, such as logging new entries or updating records over time. Unlike write mode ('w'), append mode never removes or overwrites existing content.

123456789
with open("append_example.txt", "w") as f: f.write("Original line\n") with open("append_example.txt", "a") as f: f.write("Appended line\n") with open("append_example.txt", "r") as f: result = f.read() print(result.strip())

This code first creates a file with some initial content. It then opens the same file in append mode ('a') to add a new line at the end. Finally, it reads and prints the entire file content so you can see that the new data was added to the end without deleting or modifying the original content.

Binary Mode

Binary mode is used when you need to read or write files as bytes instead of text. This is essential for working with non-text files, such as images, audio files, or executables. You combine 'b' with other file modes, such as 'rb' for reading in binary mode or 'wb' for writing in binary mode.

When you open a file in binary mode, data is read and written exactly as raw bytes. No encoding or decoding takes place, so you must handle the data as bytes objects. This prevents issues that can arise when reading or writing files that do not use standard text encoding.

12345678
byte_data = b"\x48\x65\x6c\x6c\x6f, binary world!" # This is 'Hello, binary world!' in bytes with open("sample_binary.bin", "wb") as f: f.write(byte_data) with open("sample_binary.bin", "rb") as f: read_bytes = f.read() print(read_bytes)

The code writes a byte string containing the message 'Hello, binary world!' to a file named sample_binary.bin using the write-binary mode ('wb'). The b in the mode ensures that the file is handled as binary data, not text. After writing, the file is opened again in read-binary mode ('rb') to read the raw bytes. The code then prints the human-readable representation of the bytes object.

Read and Write Mode

The r+ file mode allows you to both read from and write to an existing file. When you open a file with r+, you can read its contents, modify them, or append new data at any position. However, the file must already exist - r+ will not create a new file if it does not find one with the specified name.

This mode is useful when you need to update or process data in a file without losing its existing content. Any write operation will start from the current file position, so you can control exactly where changes occur by using file pointer methods such as seek().

1234567891011121314151617
# Writing initial content to the file with open("data.txt", "w") as f: f.write("First line\nSecond line\n") # Opening the file in r+ mode for reading and updating with open("data.txt", "r+") as f: # Reading and printing the original content original_content = f.read() print("Before update:\n" + original_content.strip()) # Moving file pointer to the beginning f.seek(0) # Overwriting the first line f.write("Updated first line\n") # Moving pointer to the start to read the updated content f.seek(0) updated_content = f.read() print("After update:\n" + updated_content.strip())

This output demonstrates that the file's first line was successfully overwritten. Using read/write mode ('r+'), you can update specific parts of a file - such as changing only the first line - without erasing or rewriting the entire file. This is useful for editing existing data while preserving other content in the file.

When you use 'r+' mode, any new data you write will overwrite existing content starting at the current file position. If the new content is shorter than the original, the leftover part of the old line remains in the file. This means partial remnants of the previous content may still appear after the new write. The file is not automatically truncated, so be aware that extra characters from the original content may persist beyond the end of your new data.

1. Which file mode should you use if you want to read an existing text file without modifying it?

2. Which file mode should you use to add new data to the end of an existing text file without deleting its current contents?

question mark

Which file mode should you use if you want to read an existing text file without modifying it?

Виберіть правильну відповідь

question mark

Which file mode should you use to add new data to the end of an existing text file without deleting its current contents?

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 2. Розділ 1

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Секція 2. Розділ 1
some-alt