Files are storage spaces where we can store data permanently. Unlike Primary Memory (RAM), Files store data in a non-volatile manner, i.e., the data is not lost in case the computer is turned off.
We can perform file operations in Python with the following three steps:
- Open a file
- Read or Write (perform operations)
- Close the file
Remember always to close the file after we have performed a file operation, as it frees up the resources that are tied to the file.
Opening a File in Python
To open a file in Python, we can use the open()
function. Let's
say we create a file called message.txt that contains the
following content:
I love programming.
I love Programiz.
We can open this file using the following code.
f = open('message.txt')
Here, the open()
function opens the file which returns a file
object that we can use to perform file operations.
The message.txt
file above is opened in read mode by default. We
can open files in multiple modes as shown below:
Modes | Description |
r (Read) |
Opens the file in the read mode. It is the default mode in Python |
w (Write) |
Opens the file in write mode. Creates a new file if it doesn't exist or clears the data in the file if it exists. |
a (Append) |
Opens the file and appends text at the end. Creates a new file if it doesn't exist . |
We could have opened the message.txt
file in different modes as
follows:
# read mode
f = open('message.txt', 'r')
# write mode
f = open('message.txt', 'w')
# append mode
f = open('message.txt','a')
Closing a File in Python
After we are done with file operations, we need to close the file. To do this,
we have the close()
function in Python.
f = open('test.txt', encoding = 'utf-8')
# perform file operations
f.close()
The above method is not safe as it doesn't properly close the file in case of an error, which is why we can use the try..finally block to handle file exceptions.
try:
f = open('message.txt', 'r')
content = f.read(6)
print(content)
more_content = f.read(12)
print(more_content)
finally:
f.close()
Even if the program encounters an error, the file will be closed, as the
finally
block will always get executed.
By the way, there is a more concise way to write the above program using the
with...open
syntax.
with open('message.txt', 'r') as f:
content = f.read(6)
print(content)
more_content = f.read(12)
print(more_content)
Reading a File in Python
We can read the content of a file using the read() method. To read a file, we must first open it:
f = open('message.txt', 'r')
content = f.read()
print(content)
f.close()
Output
I love programming. I love Programiz.
We can also read only a certain number of characters from the file with the
read()
method.
To do this, we simply need to pass the size argument to the
read()
function as below:
f = open('message.txt', 'r')
# read the first six characters
content = f.read(6)
print(content)
f.close()
Output
I love
As you can probably tell, we have read the first 6 characters of the file. If we read the same file again, it will start reading from the 7th character.
f = open('message.txt', 'r')
content = f.read(6)
print(content)
more_content = f.read(12)
print(more_content)
f.close()
Output
I love programming
Writing to Files in Python
To write into a file, we need to either open it in write w
or
append a
mode. We can then use the write()
method to
write to a file.
We need to be very careful while using the write mode because it will overwrite the file with the new content, and all previous data will be lost.
with open('message.txt','w',encoding = 'utf-8') as f:
f.write('my first file\n')
f.write('This file\n\n')
f.write('contains three lines\n')
Here,
-
If the
message.txt
file doesn't exist in your directory, the write method will create the file. -
If the
message.txt
file does exist in your directory, the write method will clear the data in it and write new lines.
The newline character \n
makes sure each
write()
method writes the line in a new line.
Appending to Files in Python
As we mentioned before, the write mode clears all the data previously present in a file and inserts new data into it.
But what if we want to add new data into a file without removing what's
already there? This is where the append 'a'
mode comes in.
Let's say we have a message.txt file with the lines:
I love Python
Python is good
Now, to append a third line into the file, we can write the following code:
with open('message.txt', 'a') as f:
f.write('\nPython is my first programming language')
The message.txt file will now be changed to:
I love Python
Python is good
Python is my first programming language
Python readlines() and writelines()
We have two more functions that extend the read()
function:
readline()
- returns a line of text in the file-
readlines()
- returns a list containing all the lines in the file
Let us open the message.txt
file that we have been working on in
read mode and use the readline()
function.
with open('message.txt', 'r') as f:
line = f.readline()
print(line)
Output
I love Python
And, we can use the readlines()
function to print the entire text
file.
with open('message.txt', 'r') as f:
lines = f.readlines()
print(lines)
Output
['I love Python\n', 'Python is good\n', 'Python is my first programming language.']
Similarly, we can use the writelines()
method if we want to write
multiple lines into a file.
with open('message.txt', 'w') as f:
lines = ['I hate Python\n', 'Python is bad ']
f.writelines(lines)
A new file named javascript.txt is created with the following contents.
Output
I hate Python Python is bad
Recommended Reading: Python os Module to Work with Directories