w1coding.comAll tutorials

Python File

Python lessons
  1. Environment Setup
  2. Introduction
  3. Control
  4. Control
  5. Loops
  6. Functions
  7. Lists
  8. Dictionary
  9. Classes
  10. Exception
  11. File
  12. Libray
  13. Date
  14. Regula
  15. JSON
  16. Web
  17. Zweb
  18. Apis
  19. Unity
  20. Llampda
  21. Iterators
  22. Generators
  23. Files
  24. Context
  25. Ilogging
  26. Multithreading
  27. Networking
  28. SQLite

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.