Day 11: File Handling (Reading and Writing Files)

Day 11: File Handling (Reading and Writing Files)

Welcome to Day 11 of our Python blog series! Today, we'll be learning file handling in Python, specifically focusing on reading from and writing to files.

File Handling

File handling in Python refers to the process of working with files stored on the computer's disk or other storage devices. It involves various operations such as reading from files, writing to files, and modifying file contents. Python provides built-in functions and methods to perform file handling operations efficiently.

Understanding access modes is essential for controlling file operations accurately. By specifying the appropriate mode when opening a file, you can define whether it will be read from, written to, or appended.

Access Modes

  • Read Mode ('r'):

    Opens the file for reading. If the file doesn't exist, it raises a FileNotFoundError. This is the default mode if no mode is specified.

  • Write Mode ('w'):
    Opens the file for writing. If the file exists, it truncates it, meaning it erases all existing content. If the file doesn't exist, it creates a new file.

  • Append Mode ('a'):
    Opens the file for writing. If the file exists, it appends new data to the end of the file. If the file doesn't exist, it creates a new file.

  • Read and Write Mode ('r+'):
    Opens the file for both reading and writing. The file pointer is placed at the beginning of the file. If the file does not exist, an I/O error gets raised.

  • Write and Read Mode ('w+'):
    Opens the file for reading and writing. If the file exists, it truncates it. If the file doesn't exist, it creates a new file. The file pointer is placed at the beginning of the file.

  • Append and Read Mode ('a+'):
    Opens the file for reading and appending. If the file doesn't exist, it creates a new file. The file pointer is placed at the end of the file.

Write to a Text File

Writing to a file in Python involves opening a file in write mode ('w') or append mode ('a') using the open() function and then using the write() method to add content to the file. Here's how you can write to a file:

#open a file in write mode ('w')
file = open("example.txt", "w")

#write data to the file
file.write("Hello, World\n")
file.write("This is a new line.")

#close the file
file.close()

a file named "example.txt" is opened in write mode ('w'). If the file already exists, its contents will be truncated (erased), and if it doesn't exist, a new file will be created. Then, the write() method is used to add content to the file.

The writelines() method in Python is used to write a sequence of strings to a file. It takes an iterable of strings as its argument and writes each string in the iterable to the file.

file.writelines["Hello, World\n", "This is a new line.\n", "Another line.\n"]

Read From a Text File

You can read data from a file in Python using the open() function in combination with file reading methods like read(), readline(), or readlines().

Reading Methods:

  • read()reads the entire content of the file as a single string.

  • readline(): Reads a single line from the file.

  • readlines(): Reads all lines of the file and returns them as a list.

#open a file in read mode
file = open("example.txt", "r")

#read the entire file
file = open("example.txt", "r")
print(file .read())

#reads a single line
file = open("example.txt", "r")
print(file .readline())

#close the file
file.close()

Closing a Text File :
Closing a text file in Python is important to ensure that all resources associated with the file are properly released. Failure to close a file can lead to resource leaks and potential issues, especially if the file is being opened and closed repeatedly or if the program is handling a large number of files.

Conclusion

In short, handling text files in Python involves:

Opening the file Use the open() function Reading from the File Use methods like read(), readline(), or readlines(). Always close the file using the close() method after reading or writing to it to release resources.