File Handling
Python provides built-in functions to read from and write to text files.
Reading from a File
open("filename.txt", "r")
Opens a file in read mode.
file.read()
Reads the entire file as a single string.
file.readline()
Reads one line at a time.
file.readlines()
Reads all lines and stores them in a list.
with open("filename.txt", "r") as file:
Best practice for handling files (auto-closes file).
.strip()
Removes leading and trailing whitespace or newline characters from a string.
Example:
Writing to a File
open("filename.txt", "w")
Opens a file in write mode (erases existing content).
open("filename.txt", "a")
Opens a file in append mode (adds content without erasing).
file.write(text)
Writes a string to the file.
file.writelines(list_of_strings)
Writes multiple lines from a list.
Example:
Closing a File
file.close()
Closes the file (not needed if using with open(...)
).
Last updated