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