Python File handling

Python File Handling

File handling is an important concept in any programming language. File handling allows the developer or programmer to store the details in non-volatile memory.

The file is the common permanent storage area to store the data. In python File handling-related operations allow developers to create new files, open existing files, read and write data from the file. Also using the python programmer allows creating a directory.

Types of files

Basically files are divided into two types based on the behavior of data store into a file.

Python File Handling

Text Files

Text files are generally used to store the text data. That can be easily read by the end-user. This type of file has an extension. txt, .docx.

Binary Files

Binary files are generally used to store binary data like images, videos, audio, etc. This type of file is widely used and is not easily read by the end-users.

Python File Handling Operations

Opening a file

Before performing any file operations, we need to open the file first. If the file is not available, then the file is automatically created by the python input function. To open the file python have an inbuilt function open() that helps users to open the file.

Syntax

open( filename, mode= 'r',buffering=-1, encoding=None, errors=None, newline=None)

The open function takes a file name as an argument and returns the File object. File object provides all methods and property that’s helped us to perform the operation on a file. Open function set file pointer at the staring of the file.

  • filename: This argument is required. In this argument, we need to pass the file name that we want to create or open. If the file is not present in the same directory, then we need to pass the path of the file as the argument.
  • mode: This argument is optional if we did not pass the value for the mode, then by default ‘r’ is considered. The mode represents the purpose of opening a file
  • buffering: This argument represents how much block is stored in the buffer area. If we did not pass any argument, then by default python does not maintain a buffer for that file.
  • encoding: This argument is used to specify the encoding format for the file.
  • errors: This is an optional string that specifies how encoding errors are to be handled. Pass ‘strict’ to raise a ValueError exception if there is an encoding error or pass ‘ignore’ to ignore errors.
  • newline: This argument controls how universal newlines works (it only applies to text mode)
Example
file=open("mydata.txt",'w')

In above example open function open the file in write mode and return the object.

File Modes

Python supports below given file modes

ModeDescription
rThis is the default file mode in open() function. This mode is used to open the existing file in reading mode. The file pointer is located at the starting of the file. If the file was not available then generate FileNotFoundError
wThis mode is used to open the file in write mode. If the specified file does not exist, then this will create a new file. If the file already exists, then old data will be overridden.
aThis mode is used to open the file in append mode. In this mode, old data is not overridden. If the file does not exist, then this will create a new file.
r+This mode is used to open the file in read and write mode. This will not override old data.
w+This mode is used to open the file in reading and write mode. This will override the old data.
a+This used to open the file in append and read mode. This will not override old data.
xThis mode is used to open the file in exclusive write mode. If the file already exists it will generate FileExistsError.

All above mentioned modes are applicable for binary file also just we need to add the suffix as ‘b’. For example ‘rb’

File Object

File Object has properties and methods that help the user to perform the operation on files and help to retrieve some information about the file

Properties

  • name: This property store the information about the file name
  • mode: This property store the information about the mode in which the file opened
  • closed: This property store a boolean value which indicates the file is opened or closed
  • encoding: This property store the encoding scheme used by the file
  • line_buffering: This property is store boolean value that given information about buffering of line. Whether any line is in buffer or not

Methods

File object has many methods related to reading and writing data into a file that we learn in the next tutorial. All other methods are listed below.

  • readable(): This method returns a boolean value that indicates whether the file is readable or not
  • writable(): This method returns a boolean value that indicates whether the file is writable or not
  • detach(): Separate the underlying buffer from the TextIOBase and return it
  • flush(): Flush write buffers, if applicable. This is not implemented for read-only and non-blocking streams
  • isatty(): This method returns a boolean value that indicates whether the file stream is interactive or not.

Example

#open the file
file=open("mydata.txt",encoding="UTF-8")
print("File name : ",file.name)
print("File Mode :",file.mode)
print("File is opened ? ",file.closed)
print("File encoding : ",file.encoding)
print("File is readable ? ",file.readable())
print("File is writable ? ",file.writable())
print("File is interactive ?",file.isatty())
#close the file
file.close()
print("File is opened ? ",file.closed)
File name :  mydata.txt
File Mode : r
File is opened ?  False
File encoding :  UTF-8
File is readable ?  True
File is writable ?  False
File is interactive ? False
File is opened ?  True

Closing a file

In python file handling, each open file must need close otherwise that consumes the memory. To close the file python file object provides a method close() that helps to close the file.

Syntax

<file-object>.close()

Example

try:
    file=open("mydata.txt")
finally:
    print("File closed")
    file.close()

In this example, we open the file in a try block and close the file in finally block that helps users to close the file even if some exception is generated at the time of performing some operation on the file. Otherwise, we can use the with block to perform file operation.

Refer Python Documentation for more information

Leave a Comment

Your email address will not be published. Required fields are marked *