Skip to content

Latest commit

 

History

History
41 lines (30 loc) · 1.62 KB

009.md

File metadata and controls

41 lines (30 loc) · 1.62 KB

Lesson 9: File Handling

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

Explanation:

  • We create a file named "example.txt" and open it in write mode ("w").
  • 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 close() method.
  • We then open the file in read mode ("r"), read its content using the read() method, and store it in the content variable.
  • Finally, we print the content and demonstrate appending to the file by opening it in append mode ("a") and using the write() method again.

Now it's time for a practical task:

Task 9:

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.