Programming in Python
Topic : Reading and writing files in Python
NAME : LOGESHWARAN . A
CLASS : II BSC IT D
REG NO: 22ITU218
DATE : 31/10/2023
SUBJECT : PYTHON
Opening a File: You use the open() function to open a file. It takes two arguments: the file
path and the mode. Common modes are:
'r': Read (default mode).
'rb': Read binary.
'rt': Read text (default for text files).
Reading the File: You can read the file using various methods, such as read(), readline(),
or readlines().
read() reads the entire file content into a single string.
readline() reads one line at a time.
readlines() reads all lines into a list.
Closing the File:
It's essential to close the file after reading to release system resources. Using a with
statement ensures the file is properly closed, as shown above.
Writing Files:
To write to a file in Python:
Opening a File:
Use the open() function with a write mode, like 'w' for text or 'wb' for binary. You can
also use 'a' to append content to an existing file.
with open('new_file.txt', 'w') as file:
Writing to the File:
Use the write() method to add content to the file.
file.write("Hello, World!\n")
Closing the File:
Always close the file when you're done writing to it. Using a with statement,
as shown above, will handle this for you
File Handling Best Practices:
Always use a with statement to open files. It ensures proper resource
management.
Check for file existence before reading or writing.
Handle exceptions when working with files, as they may not always be
available
Binary File Operations:
When dealing with binary files (e.g., images or non-text files), use 'rb' for
reading and 'wb' for writing.
Here's a complete example that reads a text file, processes its content,
and writes to another file.
# Reading a file with open('input.txt', 'r') as input_file:
content = input_file.read()
# Processing the content
processed_content = content.upper()
# Writing to a new file with
open('output.txt', 'w') as output_file:
output_file.write(processed_content)
File Paths:
When specifying file paths, it's important to use the correct format for the
operating system. You can use the os.path module to work with paths in a platform-
independent way.
Context Managers (with statement):
Using a with statement ensures that the file is automatically closed when
you're done, even if an error occurs. It's the recommended way to work with files to
avoid resource leaks.