Reading File in Python
Reading File in Python
NAME : LOGESHWARAN . A
CLASS : II BSC IT D
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:
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:
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:
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()
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.
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.