0
0
Pythonprogramming~5 mins

File system interaction basics in Python

Choose your learning style9 modes available
Introduction

We use file system interaction to save, read, and manage data on your computer. It helps programs remember information even after they stop running.

Saving a list of your favorite movies to a file.
Reading a text file with instructions or data.
Creating a new folder to organize your photos.
Checking if a file exists before opening it.
Deleting old files you no longer need.
Syntax
Python
open('filename', 'mode')

# Modes:
# 'r' - read
# 'w' - write (overwrite)
# 'a' - append (add to end)
# 'x' - create new file
# 'b' - binary mode
# 't' - text mode (default)

Always close the file after using it, or use with to handle it automatically.

File modes control how you interact with the file (read, write, append).

Examples
Open a file named 'notes.txt' to read its content safely.
Python
with open('notes.txt', 'r') as file:
    content = file.read()
Add a new line to the end of 'log.txt' without erasing existing content.
Python
with open('log.txt', 'a') as file:
    file.write('New entry\n')
Open 'data.txt' to write text, then close the file to save changes.
Python
file = open('data.txt', 'w')
file.write('Hello world!')
file.close()
Sample Program

This program creates a file called 'example.txt', writes two lines of text, then reads and prints the content.

Python
filename = 'example.txt'

# Write some text to the file
with open(filename, 'w') as file:
    file.write('Hello, file system!\n')
    file.write('This is a test file.')

# Read the text back from the file
with open(filename, 'r') as file:
    content = file.read()

print('File content:')
print(content)
OutputSuccess
Important Notes

Using with open(...) is safer because it closes the file automatically.

Writing with mode 'w' erases the old content, so be careful.

Reading a file that does not exist will cause an error.

Summary

Files let your program save and load information on your computer.

Use open() with modes like 'r', 'w', and 'a' to read, write, or add to files.

Always close files or use with to avoid problems.