Chapter 4
Chapter 4
file1 = open("file1.txt")
Here, we have created a file object named file1 . Now, we can use this
object to work with files.
More on File Opening
Different File Opening Modes
Python allows us to open files in different modes (read, write, append, etc.), based
on which we can perform different file operations. For example,
file1 = open("file1.txt")
Here, we are opening the file in the read mode (we can only read the content, not
modify it).
Note: By default, Python files are open in read mode. Hence, the
code open("file1.txt", "r") is equivalent to open("file1.txt") .
Mode Description
a Open a file in appending mode (adds content at the end of the file)
file_path = "/home/user/documents/file1.txt"
file1 = open(file_path)
Output
In the above example, the code file1.read() reads the content of the file
and stores it in the read_content variable.
Note: If you need clarification about how the code file1.read() works,
please visit Working of Python Objects.
When we run the above code, we will see the specified content inside the
file.
Writing to a Python File
Be Careful While Writing to a File
If we try to perform the write operation to a file that already has some content, the
new content will replace the existing ones. For example,
When we run the above code, the new content will replace any existing content
in file2.txt.
Writing to an Existing Python File
Note: If we try to open a file that doesn't exist, a new file is created, and
the write() method will add the content to the file.
# open a file
file1 = open("file1.txt", "r")
Output
Note: Closing a file will free up the resources that are tied to the file.
Hence, it is a good programming practice to always close the file.
Opening a Python File Using with...open
In Python, there is a better way to open a file using with...open . For
example,
Output
Note: Since we don't have to worry about closing the file, make a habit of
using the with...open syntax.
try:
file1 = open("file1.txt", "r")
read_content = file1.read()
print(read_content)
finally:
# close the file
file1.close()
Output
Here, the finally block is always executed, so we have kept the close() function
inside it. This ensures that the file will always be closed.
To learn more about exceptions, visit Python Exception Handling.
Note: Make a habit of using the with...open syntax while working with files so you
don't have to worry about closing the file.
Here is the complete list of methods in text mode with a brief description:
Method Description