Table of Contents
In this comprehensive tutorial, we will delve deep into the power of Python’s built-in functions for file I/O operations, focusing on how to read and write data to files. Understanding file manipulation is essential for building Python applications that need to interact with external data sources.
Introduction to the Print Function in Python
Before we dive into file handling, let’s start with the print()
function. It's one of the most commonly used built-in functions in Python. Its purpose is simple: it outputs data to the console or any specified output device. Here's a basic example of using print()
to display a string:
# Using print to display a string
print("Hello, Python!")
Output:
Hello, Python!
This prints the string on the screen. Now, let’s combine a variable with print()
.
# Printing string and variable together
x = 10
print("The value of x is", x)
Output:
The value of x is 10
In this example, the value of x
is printed alongside the string. You can also customize the separator between values in the print()
function using the sep
parameter:
print(1, 3, 5, 7, 8, sep="*")
Output:
1*3*5*7*8
Python allows you to adjust how items are separated and formatted in the output with additional arguments such as sep
(separator) and end
(line ending). The default separator is a space, and by default, the output ends with a newline.
Formatting Output in Python
You can format the output to make it more readable or visually appealing. The format()
method can be used with string objects to insert values in specific places within a string.
# Using the format() method for output formatting
x = 10
y = 20
print("The value of x is {} and the value of y is {}".format(x, y))
Output:
The value of x is 10 and the value of y is 20
You can also reorder or format the output by using positional or keyword arguments:
# Reordering using positional arguments
print("I like {0} and also {1}".format("Tea", "Milk"))
print("I like {1} and also {0}".format("Tea", "Milk"))
# Using keyword arguments
print("Hi {name}, {greet}".format(greet="Welcome", name="Thakur"))
Output:
I like Tea and also Milk
I like Milk and also Tea
Hi Thakur, Welcome
Using the Input Function
The input()
function allows you to take input from the user. It can capture various data types such as strings, numbers, and lists.
# Taking user input
number = input("Enter a number: ")
print("You entered:", number)
Output:
Enter a number: 10
You entered: 10
Keep in mind that the input()
function returns data as a string, even if you enter a number. You can convert it to an integer or other types if needed.
Working with Files in Python
Python provides a robust set of functions to read from and write to files. Let’s explore the process of file handling in Python, including how to open, read, write, and close files.
Opening Files in Python
To begin working with files, use Python's built-in open()
function. The syntax is:
file_object = open(file_name, mode)
The mode
argument specifies how you want to interact with the file. Common modes include:
"r"
– Read (default mode, will raise an error if the file doesn't exist)."w"
– Write (creates a new file or overwrites an existing file)."a"
– Append (adds data to the end of an existing file)."x"
– Create (creates a new file, but will return an error if the file exists).
Let’s look at an example of reading a file:
# Open a file in read mode
file = open("example.txt", "r")
print(file.read())
file.close()
In this example, the file’s contents are read and printed. Always remember to close the file after you're done to free up resources.
Reading Specific Parts of a File
You can read parts of a file by specifying the number of characters to read or by reading one line at a time:
# Reading the first 5 characters
file = open("example.txt", "r")
print(file.read(5))
file.close()
# Reading one line at a time
file = open("example.txt", "r")
print(file.readline())
file.close()
You can also loop through the lines of a file:
file = open("example.txt", "r")
for line in file:
print(line)
file.close()
Writing to Files
To write to a file, you can open the file in write ("w"
) or append ("a"
) mode. Here's an example of adding text to a file:
# Writing to a file
file = open("output.txt", "a")
file.write("This is a new line of text.\n")
file.close()
To overwrite the file with new content, use the "w"
mode:
file = open("output.txt", "w")
file.write("This file has been overwritten.")
file.close()
Closing Files
After finishing with a file, always use the close()
method to close the file:
file = open("output.txt", "r")
print(file.read())
file.close()
Python automatically closes files when a file object is reassigned or when the program ends, but it’s a good practice to explicitly close files when done.
File Creation
To create a new file, you can use the "x"
mode with the open()
function:
file = open("newfile.txt", "x")
file.close()
Alternatively, you can use "w"
to create a file if it doesn’t already exist.

Zeyan Rhys is a Python developer and content writer at Syntax Notes, where he turns complex coding concepts into simple, beginner-friendly tutorials. He’s passionate about helping others understand Python in a way that actually clicks.