On Day 9, we learned about file handling in programming. File handling is the process of creating, reading, updating, and deleting files in a computer's file system.
Python is a versatile language that can handle a variety of tasks with ease. One of the most common tasks when working with Python is file handling. In this post, we'll explore how to handle files in Python and some of the common operations you can perform on files.
Before you can manipulate a file, you need to open it. To open a file in Python, you can use the open() builtin function.
The open() function takes two arguments:
file nameand the mode in which you want to open the file.For example, to open a file named "sample.txt" in read-only mode, you would use the following code:
file = open("sample.txt", "r")
contents = file.read()
print(contents)
To write to a file, you can use the write() function. The write() function writes the specified string to the file. For example:
file = open("sample.txt", "w")
file.write("Hello, World!")
file.close()
This code opens the "sample.txt" file in write mode, writes the string "Hello, World!" to the file, and then closes the file.
To append to a file, you can use the write() function with the "a" mode. For example: