File handling is an essential skill in programming, allowing us to read from and write to files. Python provides built-in functions and methods for working with files, making it easy to perform file-related operations.
Let’s explore how to handle files in Python:
# Creating and writing to a file file = open("example.txt", "w") # Open the file in write mode file.write("Hello, world!\n") file.write("This is a sample text.") file.close() # Close the file # Reading from a file file = open("example.txt", "r") # Open the file in read mode content = file.read() file.close() # Close the file print("File content:") print(content) # Appending to a file file = open("example.txt", "a") # Open the file in append mode file.write("\nThis line is appended.") file.close() # Close the file
- We create a file named “example.txt” and open it in write mode (
- We use the
write()method to write content to the file, including a newline character (
"\n") to separate lines.
- After writing, we close the file using the
- We then open the file in read mode (
"r"), read its content using the
read()method, and store it in the
- Finally, we print the content and demonstrate appending to the file by opening it in append mode (
"a") and using the
Now it’s time for a practical task:
Write a Python program that reads the content of a text file named “data.txt” and counts the number of lines in the file. Print the count at the end.
Once you’ve completed the task, you can proceed to the next lesson.