File I/O and Modules in Python

Python tutorial · PySpark.in

Introduction to File I/O

File I/O (Input/Output) in Python means reading from and writing to files stored on your system.

It allows you to:

Opening and Closing Files

Python provides the built-in function open() to work with files.

Syntax:

PLAINTEXT
1file_object = open(filename, mode)
▶ Output will appear here.

Mode

Description

'r'

Read (default). File must exist.

'w'

Write. Creates a new file or overwrites an existing one.

'a'

Append. Adds data at the end of the file.

'r+'

Read and write. File must exist.

'w+'

Write and read. Creates new file or overwrites.

'a+'

Append and read. Creates file if not exist.

Reading from a File

Example:

PLAINTEXT
1# Open file in read mode
2file = open("data.txt", "r")
3# Read full content
4content = file.read()
5print(content)
6# Close file
7file.close()
▶ Output will appear here.

Note: Always close a file after using it to free up system resources.

Other Read Methods

Method

Description

file.read(size)

Reads specified number of bytes.

file.readline()

Reads one line at a time.

file.readlines()

Reads all lines and returns a list.

Writing to a File

Example (Write Mode):

PLAINTEXT
1with open("output.txt", "w") as file:
2 file.write("Hello, this is a new file!\n")
3 file.write("Python makes file handling easy.")
▶ Output will appear here.

If the file exists, it will overwrite it.

Example (Append Mode):

PLAINTEXT
1with open("output.txt", "a") as file:
2 file.write("\nThis line is added later.")
▶ Output will appear here.

This adds content at the end of the file without deleting previous data.

Reading and Writing Together

PLAINTEXT
1with open("data.txt", "r+") as file:
2 content = file.read()
3 print("Before writing:", content)
4 file.write("\nNew line added!")
▶ Output will appear here.

More Python tutorials

All tutorials · Try the free PySpark compiler · Practice challenges