Latest posts


File operations and File Handling in Python | Modes of file in Python | Methods of file object in Python

In the last post on Python programming, we learned about Exception handling in Python programming. Now in this post, we are going to learn about, Exploring File Input / Output in Python: Reading and Writing to Files.

We know that Python, a universal programming language, offers powerful features for reading from and writing to files. File input/output (I/O) operations are crucial for handling data persistence, logging, and interacting with external resources. In this post, we will explore the fundamentals of file I/O in Python, covering topics such as opening and closing files, reading data from files, writing data to files, and various file modes. By the end of this article, you will have a solid understanding of how to effectively work with files in Python and be able to leverage this knowledge in your own projects.

1. Opening and Closing Files :

To begin working with files in Python, the first step is to open the file. The open() function is used for this purpose, and it requires the filename as the argument. Additionally, you can specify the mode in which the file should be opened, such as read mode ('r'), write mode ('w'), or append mode ('a').

Syntax :
file_object = open(filename, mode)

Example 1 : 
file = open('data.txt', 'r')

Example 2 : 
file = open('output.txt', 'w')

So in 1st example, we opened a file 'data.txt', with mode 'r' which is the reading mode. Because of that, the file is opened in the system with reading access for the user. It means the users don't allow to make changes to the file.

In the 2nd example of the file, we again opened the file 'data.txt', but now the mode is 'w' which is writing mode. Now the file is opened with writing accesses, just because of that, the user can able to make changes to the file, but they cannot able to read the file or see the file content.

 Once you are done working with a file, it's essential to close it using the close() method to free up system resources. Failing to close files can result in data corruption or loss.

Syntax : 

Example : 

 So, first, we opened a file 'data.txt' with an object 'file', and with mode 'r', after that, we again opened file 'data.txt' with the same object 'file', and with mode 'w'.
Now in this example, we have closed the, opened file by using the function .close().

By closing this file, we secured this file from data loss and file corruption.

2. Reading from Files :

Python provides various methods for reading data from files, including reading the entire file, reading line by line, or reading a specific number of characters. Let's explore these approaches:

A. Reading the entire file:

To read the entire contents of a file, you can use the read() method. It returns a string containing the file's contents.

Syntax :

Example : 
file = open('data.txt', 'r')
content =

So in this example, we have opened a file 'data.txt' with mode 'r', and stored it in a file object 'file'. After that, we created a new variable 'content', to use our .read() method on the file object. Now, the variable 'content' stores all the string data present in the file 'data.txt'. After that, we closed this file using .close().

B. Reading line by line:

To read a file line by line, you can use the readline() method. It reads one line at a time, and with each subsequent call, it moves to the next line.

By using this method, we can able to read the file content line by line. This method basically prints a single line, so to read all the lines one by one, we need to create more than one object of readline().

Syntax : 

Example : 
file = open('data.txt', 'r')
line1 = file.readline()
line2 = file.readline()

C. Reading a specific number of characters:

To read a specific number of characters from a file, you can use the read(n) method, where 'n' represents the number of characters to be read.

Syntax :

Example : 
file = open('data.txt', 'r')
characters =

In the output of this program, it will return only the first 10 characters on file.

3. Writing to File :

Python allows you to write data to files using the file object's .write() method. You can write strings or use conversion functions to convert other data types to strings before writing.

So we have seen, how to read the contents of the file using the .read() method and the .readline() method.

Now we are going to see, how to write content in a file.

Syntax : 

Example : 
file = open('output.txt', 'w')
file.write("Hello, World!")

In write mode, if the specified file does not exist, Python will create a new file. However, if the file already exists, opening it in write mode will truncate the file, erasing its previous content.

To append data to an existing file without deleting its previous content, you can open the file in append mode ('a').

Syntax : 
file_object = open(filename, 'a')

Example : 
file = open('output.txt', 'a')
file.write("Appending new content!")

In the example above, the text "Appending new content!" will be added to the end of the file without affecting its existing contents.

4. File Modes and Handling Errors : 

Python provides different file modes to handle various scenarios. Here are some commonly used file modes:

'r' Read mode (default). Opens the file for reading.
'r' Read mode (default). Opens the file for reading.
'w' Write mode. Opens the file for writing. Creates a new file if it doesn't exist, and truncates the file if it does.
'a' Append mode. Opens the file for appending. Creates a new file if it doesn't exist.
'x' Exclusive creation mode. Opens a file for exclusive creation. Fails if the file already exists.
'b' Binary mode. Opens the file in binary mode.
't' Text mode (default). Opens the file in text mode.
'+' Open a file for updating (reading and writing)

It's crucial to handle potential errors that may occur while working with files. Python allows you to handle exceptions using try-except blocks. Here's an example:
    file = open('data.txt', 'r')
    # Perform operations on the file
except FileNotFoundError:
    print("The file does not exist.")
except IOError:
    print("An error occurred while reading the file.")

In the example above, we open a file in read mode and perform operations on it. If a FileNotFoundError occurs, it means that the file does not exist, and we handle it accordingly. Similarly, if an IOError occurs during file operations, we handle that exception as well.

5. Methods of file object :

There are various methods available with the file object. Some of them have been used in the above examples.

close() Closes an opened file. It has no effect if the file is already closed.
detach() Separates the underlying binary buffer from the TextIOBase and returns it.
fileno() Returns an integer number (file descriptor) of the file.
flush() AFlushes the write buffer of the file stream.
isatty() Returns True if the file stream is interactive.
readline(n=-1) Reads and returns one line from the file. Reads in at most n bytes if specified.
read(n) Reads at most n characters from the file. Reads till the end of the file if it is negative or None.
readable() Returns True if the file stream can be read from.
readlines(n=-1) Reads and returns a list of lines from the file. Reads in at most n bytes/characters if specified.
seek(offset,from=SEEK_SET) Changes the file position to offset bytes, in reference to from (start, current, end).
seekable() Returns True if the file stream supports random access.
tell() Returns an integer that represents the current position of the file's object.
truncate(size=None) Resizes the file stream to size bytes. If size is not specified, resize to the current location.
writable() Returns True if the file stream can be written to.
write(s) Writes the string s to the file and returns the number of characters written.
writelines(lines) Writes a list of lines to the file.

6. Conclusion :

File I/O operations play a vital role in many programming tasks. Python provides convenient methods and syntax to read from and write to files. By mastering file I/O concepts, you gain the ability to store and retrieve data, manipulate external files, and create more sophisticated programs.

So, we covered the fundamentals of file I/O in Python, including opening and closing files, reading data using various methods, writing data to files, understanding file modes, and handling potential errors. Armed with this knowledge, you can confidently work with files, implement data persistence, and perform file-based operations in your Python projects.

Remember to practice good file handling practices, such as closing files after use and handling potential errors. With these skills, you can efficiently handle file-based operations and harness the full power of Python in your programming endeavors.

We hope it will help you to learn more about Python programming...!

Thank You !!!

Also Visit

Post a Comment