In Python, reading from and writing to text files is a common task that can be accomplished using built-in functions.
Reading a File:
To read a file, use the open() function with the ‘r’ mode (read mode). Use methods like read(), readline(), or readlines() to access the file content.
python
with open(‘file.txt’, ‘r’) as file:
content = file.read()
Writing to a File:
To write to a file, use the open() function with the ‘w’ mode (write mode) or ‘a’ mode (append mode). The write() method writes data to the file.
python
with open(‘file.txt’, ‘w’) as file:
file.write(‘Hello, World!’)
Example:
python
# Writing to a file
with open(‘example.txt’, ‘w’) as file:
file.write(‘Python is fun!’)
# Reading from a file
with open(‘example.txt’, ‘r’) as file:
print(file.read())
Always use with to ensure files are properly closed after their operations are done.