You are on page 1of 2

Python File Operations

Most importantly there are 4 types of operations that can be handled by Python on files:
Open
Read
Write
Close
Other operations include:
Rename
Delete

Opening Files
Python has an in-built function called open() to open a file. It takes two string arguments:
1. The file path including the file name and the extension we want to open, is to be passed as a string
2. The mode in which we want to open the file, to be passed as a string.
The syntax for opening a file:
Syntax:
file_object = open(file_name, mode)

Read Only ('r’):


.
Write Only ('w’):
Append Only ('a’):
Read and Write ('r+’):
Write and Read ('w+’): \
Append and Read (‘a+’):

Python Read From File


In order to read a file in python, we must open the file in read mode.
There are three ways in which we can read the files in python.
read( )
readline( )
readlines( )

# open a file
file1 = open("test.txt", "r")
# read the file
read_content = file1.read()
print(read_content)
Output
This is a test file.
Hello from the test file
Write to a File in Python
The write() method:
This function inserts the string into the text file on a single line.
If we want to add content to existing file, test.txt, first we need to open it in the ‘w’ write mode and
use the .write() method on file.

file = open("myfile.txt", 'w')


file.write("Hello There\n")

The writelines() method:


This function inserts multiple strings at the same time. A list of string elements is created, and each
string is
then added to the text file.
file = open("test.txt", 'r')
f.writelines(["Hello World ", "You are welcome"])
Closing Files in Python
When we are done with performing operations on the file, we need to properly close the file.
Closing a file will free up the resources that were tied with the file. It is done using the close() method in
Python.

For example,
# open a file
file1 = open("test.txt", "r")

# read the file


read_content = file1.read()
print(read_content)

# close the file


file1.close()

You might also like