Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
The very basics of text files
2. Text files in Python – first example
with statement and exception handling


Great! Let's start with a very basic example in which we'll open a file and print its contents:

file = open('employees.txt')

And that's it! Python comes with some built-in file functions that are easy to use.

  • The open() function opens a file whose filename is given as the argument. To clarify, open() doesn't actually open any files; rather, it returns a so-called file object that represents the corresponding file on your computer. You must assign that object to a variable if you want to use it. In our case, that variable is simply called file.
  • To get the entire contents of the file, use As you can see, you can pass that result to print() to show the file's contents in the console.
  • file.close() closes the file so you can no longer read it (unless you open it again). Remember to put this statement in your code when you're done with a file.


Open a file named daily_sales.txt and print its contents. Close the file afterwards.

Stuck? Here's a hint!

The argument of open() should be 'daily_sales.txt'.