How to perform file operations in Python?
Published on Aug. 22, 2023, 12:17 p.m.
File operations are a crucial part of any programming language, and Python provides several methods for performing file operations. Here are some of the most common tasks:
- Opening a file: To open a file in Python, you can use the
open()
function. For example, to open a file named “test.txt” in read mode, you can use the following code:
file = open("test.txt", "r")
- Reading a file: To read the contents of a file, you can use the
read()
method. For example:
file = open("test.txt", "r")
content = file.read()
- Writing to a file: To write data to a file, you can use the
write()
method. For example:
file = open("test.txt", "w")
file.write("Hello, World!")
- Closing a file: It’s important to close the file once you’re done with it, to free up system resources. You can use the
close()
method to close a file. For example:
file = open("test.txt", "r")
content = file.read()
file.close()
- Checking if a file exists: To check if a file exists on the system, you can use the
os.path.isfile()
method. For example:
import os
file_exists = os.path.isfile("test.txt") # returns True if file exists, False otherwise
These are just a few examples of common file operations in Python. Python provides many more file manipulation methods and functions, so it’s a good idea to familiarize yourself with the Python file operations.