Python - Reading and Writing Files
25.
How can you handle encoding and decoding issues when working with files?
Handling encoding and decoding issues when working with files in Python is crucial to ensure proper reading and writing of text data, especially when dealing with different character encodings. The open()
function allows you to specify the encoding using the encoding
parameter.
Here's an example program that demonstrates how to handle encoding and decoding issues:
# Example data with non-ASCII characters
text_data = "Café au Lait"
# Writing text data to a file with a specific encoding
file_path = 'example_text_file.txt'
with open(file_path, 'w', encoding='utf-8') as text_file:
text_file.write(text_data)
# Reading text data from the file with the same encoding
with open(file_path, 'r', encoding='utf-8') as text_file:
read_text_data = text_file.read()
print("Read Text Data:")
print(read_text_data)
In this example, the program writes text data to a file using the 'utf-8'
encoding and then reads the text data back from the file using the same encoding. Specifying the encoding is important to handle characters outside the ASCII range correctly.
The output of the program will be:
Read Text Data: Café au Lait
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers