File Handling In Python

File Handling in Python: A Comprehensive Guide

Let’s delve into File Handling in Python and its applications. In this article, we will guide both beginner and experienced Python enthusiasts through the basics of file handling – reading, writing, and managing files using Python. We will also look at some real-life examples to better understand these concepts.


File Handling In Python
File Handling In Python

What is File Handling?


File handling is a crucial part of any web application. It refers to the operations involving creating, editing, reading, and deleting files. Python gives you easy-to-use tools and techniques for efficient file handling. The key function for working text files is the open() function.

File Handling Operations


Following are fundamental file handling operations:

  1. Open a File: To open a file in Python, we use the built-in open() function.
  2. Read a File: ‘read’ is a built-in method used to read a file’s contents. There are various methods available like read(), readline(), readlines().
  3. Write to a File: ‘write’ is a built-in method used for writing data to a file. There are two ways—write() and writelines().
  4. Appending to a file: Appending means adding new data at the end of a file. This doesn’t erase existing data.
  5. Close a File: After our work with the file is competent, we should close it using the close() method.

Let’s discuss these operations in detail.

Opening a File


Python has a built-in function called open() for opening a file. This function returns a file object which can be used to read, write and modify the file.

f = open('myfile.txt') 

In this example, ‘myfile.txt’ is the name of the file to be opened. If the file is in a different directory, specify the file path.

Reading a File


You can read a file in Python using the read(), readline(), or readlines() methods.

read():

In Python, the read() method reads the content of the file and stores it into a string. Here is an example:

f = open('myfile.txt', 'r')
print(f.read())
f.close()

readline():

readline() reads a file line-by-line instead of pulling the content of the whole file at once. Consider this:

f = open('myfile.txt', 'r')
print(f.readline())
f.close()

readlines():

readlines() function reads all the lines at once and returns a list of strings, where each string is a line from the file.

f = open('myfile.txt', 'r')
print(f.readlines())
f.close()

Writing to a file


Python provides write() function to write data into a file.

f = open('myfile.txt', 'w')
f.write('Hello, Python Times!')
f.close()

This will write the text ‘Hello, Python Times!’ into the file ‘myfile.txt’. Remember, if the file already exists, the write() function will overwrite the existing data.

Appending to a file


Appending is adding data to a file without deleting existing data. Use ‘a’ as the second argument to open() function.

f = open('myfile.txt', 'a')
f.write('\nThis is appended text.')
f.close()

This will not erase the existing data, but add new data at the end.

Closing a file


After completing our operations on a file, it’s necessary to close it. Python has a close() method for this.

f = open('myfile.txt', 'r')
print(f.read())
f.close()

File Modes in Python


When opening a file, we can specify different modes. Here’s a quick rundown:

  • ‘r’ – Read mode
  • ‘w’ – Write mode (also creates a new file if it doesn’t exist already)
  • ‘a’ – Appending mode, adds new data to the end of the file (also creates a file if it doesn’t exist)
  • ‘t’ – Text mode
  • ‘b’ – Binary mode
  • ‘+’ – Update mode, for both reading and writing

See the modes in action below:

# Open for reading (default)
f = open('myfile.txt')

# Open for writing
f = open('myfile.txt', 'w')

# Open for appending
f = open('myfile.txt', 'a')

# Open for reading in binary
f = open('myfile.txt', 'b')

Handling File Errors


What happens if you try to open a nonexistent file? Python raises an error. To handle such situations, Python provides the try…except block.

try:
  f = open('myfile.txt')
except:
  print('Something went wrong')
finally:
  f.close()

Here, the try block will try to open the nonexistent file. If it fails, the except block will run.

Conclusion


In this article, we covered the basics of file handling in Python. From reading, writing, and appending data to files to understanding different file modes and working with exceptions, Python provides a robust and straightforward way to handle file operations. Enjoy exploring these operations with your own data and projects!


Remember, practice makes perfect. Try out these file operations with a basic .txt file and move on to more complex tasks as you get comfortable with these operations. The power of Python lies in its simplicity and efficiency, which can cut down your coding efforts significantly. Happy coding!


Stay up to-date with Python Times for more articles on Python. Also, do submit your doubt/queries/suggestions. Happy learning with Python Times.

Share this article:

Leave a Comment