Home » Python

Opening, closing a file/open(), close() functions in Python

In this tutorial, we are going to learn about the basic operations of file handling in python, we will learn about the file opening with various mode and file closing().
Submitted by IncludeHelp, on December 27, 2018

open() function

It is used to open a file in specified modes.

The file opening modes are:

  1. "r"Read mode (which is a default mode) – it opens a file for reading the data and if the file does not exist, it returns an error.
  2. "a"Append mode – it opens a file for appending the data, it creates a new file if the file does not exist.
  3. "w"Write mode – it opens a file in write mode to write data in it, if the file is opened in write mode then existing data will be removed, it also creates a file, if the file does not exist.
  4. "x"Creates a file, if the file already exists, it returns an error.

File types

There are two file types

  1. Text mode – to specify the file as text file, we use "t" with the file mode.
  2. Binary mode – to specify the file as a binary file, we use "b" with the file mode.

Syntax to open a file

    file_object = open(file_name, [mode])

Here, "mode" is optional, if we do not specify any mode – the default mode will be "rt" that means "text file in read-only mode".

close() function

It is used to close an opened file, if the file does not exist, it returns an error.

Syntax:

    file_object.close();

Example 1:

In this example, we are creating a file "file.txt" (i.e. opening a file in write mode) and closing it, "file1.txt" will be created and saved. Then we are opening "file1.txt" in read mode and closing it.

After that, we are printing "Operation successful."

#Python Example to open and close a file 

# creating a file in write mode 
f = open("file1.txt","wt")
# closing it
f.close()

# opening a file1.txt in read mode
f = open("file1.txt","rt")
# closing it
f.close()

print("Operation successful.")

Output

Operation successful.

Example 2:

In this example, we are opening a file "abc.txt" which does not exist in the memory and when we will open it, the program will return an error "FileNotFoundError".

#Python Example to open and close a file 

# opening a file which does not exist
f = open("abc.txt", "rt")
# closing it
f.close()

print("Operation successful.")

Output

    f = open("abc.txt", "rt")
FileNotFoundError: [Errno 2] No such file or directory: 'abc.txt'


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.