file

Python File Handling

Python File Handling

Python provides functions to work with files. You can read from and write to files using built-in functions like open(), read(), and write().

Opening a File

To open a file, use the open() function, which takes the file name and the mode in which you want to open the file (e.g., 'r' for reading, 'w' for writing):

      
        file = open("example.txt", "w")
        file.write("Hello, world!")
        file.close()
      
    

This code opens (or creates) a file called example.txt, writes "Hello, world!" to it, and then closes the file.

Reading from a File

To read the contents of a file, use the read() function:

      
        file = open("example.txt", "r")
        content = file.read()
        print(content)
        file.close()
      
    

This reads the content of the file and prints it.

Activity

Try It Yourself!

Create a program that writes your name to a file and then reads and prints the content of the file.

Quick Quiz

Quick Quiz

  1. What function do you use to open a file in Python?
  2. How do you write to a file in Python?

Answers: Use open() to open a file. Use write() to write content to a file.