In this comprehensive lesson, we'll delve into writing files in Python. This skill is crucial for saving and loading data, creating logs, and interacting with various types of files such as text, JSON, XML, and more. Whether you're a beginner or an intermediate learner, this lesson will provide you with a thorough understanding of the topic.
A file is a collection of data stored on a computer. Files can contain text, images, audio, video, and other types of data. In Python, we work with files to store and retrieve data.
Writing files in Python allows us to:
Python provides several built-in functions for working with files, including:
open(): Opens a file with specified modewrite(): Writes data to a fileclose(): Closes a fileTo open a file in write mode (w), use the open() function:
file = open('example.txt', 'w')Here, we create a file object called file that points to a file named example.txt in write mode.
Pro Tip: Always close the file after you're done writing to it:
file.close()To write data to a file, use the write() function:
file.write('Hello, World!')This writes the string 'Hello, World!' to the file.
Let's write a simple program that writes the user's name and age to a file:
name = input('Enter your name: ')
age = int(input('Enter your age: '))
file = open('user_data.txt', 'w')
file.write(f'Name: {name}\n')
file.write(f'Age: {age}\n')
file.close()When you run this program, it will prompt you to enter your name and age, and then it will write that data to a file named user_data.txt.
What mode does the `open()` function open a file in when the argument is `'w'`?
To write to an existing file without overwriting its content, use the append mode ('a'):
file = open('example.txt', 'a')
file.write('More text!')
file.close()This writes 'More text!' to the end of the existing file.
When working with files, it's essential to handle exceptions to ensure your program can recover gracefully if an error occurs:
try:
file = open('example.txt', 'w')
file.write('Hello, World!')
file.close()
except FileNotFoundError:
print('Error: The file does not exist!')This code attempts to open a file called example.txt in write mode. If the file doesn't exist, it will print an error message.
Which exception is raised when a file is not found while opening a file in Python?
In this lesson, we covered writing files in Python, including:
With this knowledge, you're well on your way to mastering file operations in Python. Happy coding! 🚀