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

Instruction

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

file = open('employees.txt')
print(file.read())
file.close()

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 file.read(). 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.

Exercise

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'.