Beginner’s Guide to Python – Prerequisite for Mastering Machine Learning
About Lesson

File handling is an essential aspect of programming that allows you to read from and write to files on your computer. Python provides built-in functions and methods for working with files.

Opening a File

To open a file in Python, you can use the open() function. The open() function takes two parameters: the file path and the mode in which you want to open the file (e.g., read, write, append). Here’s an example:

python
# Open a file in read mode
file = open("data.txt", "r")

Reading from a File

Once you’ve opened a file, you can read its contents using various methods such as read(), readline(), or readlines(). Here’s an example:

python
# Read the entire contents of the file
contents = file.read()

print(contents)

# Close the file
file.close()

Writing to a File

You can write data to a file using the write() method. Here’s an example:

python
# Open a file in write mode
file = open("output.txt", "w")
# Write data to the file
file.write("Hello, World!")

# Close the file
file.close()

Appending to a File

You can append data to an existing file using the append() mode. Here’s an example:

python
# Open a file in append mode
file = open("output.txt", "a")
# Append data to the file
file.write("nThis is a new line.")
# Close the file
file.close()

Understanding file handling is essential for working with external data and storing information persistently. In the next chapter, we’ll explore exception handling, which allows you to gracefully handle errors and unexpected situations in your Python programs.

Join the conversation