Notes
Reading from a file
To read from a file, use the open() function with
the file name as an argument, and use
the read() method on the resulting file object.
with open('filename.txt', 'r') as file:
content = file.read()
Writing to a file
To write to a file, use the open() function with
the file name and the 'w' mode as an argument,
and use the write() method on the resulting file
object.
with open('filename.txt', 'w') as file:
file.write('This is a sample text.')
Appending to a file
To append to a file, use the open() function with
the file name and the 'a' mode as an argument,
and use the write() method on the resulting file
object.
with open('filename.txt', 'a') as file:
file.write('\nThis is a new line.')
Closing a file
It is a good practice to close a file once you are
done with it. This can be done using
the close() method on the file object. However,
, using the with statement will automatically close
the file when the operations inside it are
completed.
with open('filename.txt', 'r') as file:
content = file.read()
file.close() # not needed when using 'with'
Handling exceptions
When working with files, it is important to handle
exceptions that may occur during file input/output
operations, such as FileNotFoundError . This can
be done using a try-except block.
try:
with open('filename.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print('File not found.')
Context manager
The with statement can be used as a context
manager for files, ensuring that they are properly
closed after the block of code is executed.
with open('filename.txt', 'r') as file:
content = file.read()
# file is automatically closed here
File input/output operations in Python allow you to read
from and write to files on the system. This is crucial for
data persistence and manipulation. Here’s a breakdown of