Python provides built-in support to work with files stored on your system. Using simple functions like open(), read(), and write(), you can store data permanently, load it back, and process it whenever needed.
with statement.open() and used to read/write data."r", "w", "a", "x", "rb", etc."r", "w") vs binary files ("rb", "wb").read(), readline(), readlines() for different reading needs.The basic syntax for opening a file in Python is:
file_object = open("filename.txt", "mode")
# perform file operations
file_object.close()
Common file modes include:
"r" – Read (default). Fails if the file does not exist."w" – Write. Creates a new file or overwrites an existing file."a" – Append. Adds content to the end of the file without deleting existing data."x" – Create. Creates a new file, error if the file already exists."rb", "wb", "ab" – Binary modes for read/write/append.Using the with statement is the recommended way to handle files because it ensures the file is closed automatically, even if an error occurs.
This example opens a file in read mode and then closes it explicitly.
file = open("example.txt", "r") # Open file in read mode
file.close()
Here, the with statement automatically closes the file once the block finishes.
with open("example.txt", "r") as file:
content = file.read()
print(content) # File is automatically closed
Use readline() to read one line at a time and readlines() to get all lines in a list.
with open("example.txt", "r") as file:
print(file.readline()) # Reads one line
print(file.readlines()) # Reads all remaining lines into a list
Opening a file in write mode ("w") will create the file if it does not exist.
with open("example.txt", "w") as file:
file.write("Hello, World!") # Writes text to file
open("example.txt", "r") tries to open the file.readline() and readlines().with statement to automatically close files.read(), readline(), and readlines() appropriately."a" mode.