

We must always close the opened files after we're done with them to release our computer resources and avoid raising exceptions. The close() method closes the file in the last line.

In the second line of the code above, we use the read() method to read the entire file and print its content. In the first line, the output of the open() function is assigned to the f variable, an object representing the text file. In the code above, the open() function opens the text file in the reading mode, allowing us to grab information from the file without accidentally changing it. Namespaces are one honking great idea - let's do more of those! If the implementation is easy to explain, it may be a good idea. If the implementation is hard to explain, it's a bad idea. There should be one- and preferably only one -obvious way to do it.Īlthough that way may not be obvious at first unless you're Dutch.Īlthough never is often better than *right* now. In the face of ambiguity, refuse the temptation to guess. Special cases aren't special enough to break the rules. f = open('zen_of_python.txt', 'r')į.close() The Zen of Python, by Tim Peters Download the text file containing the Zen of Python, and store it in the same path as your code. The open() function provides a few different modes that we'll discuss later in this tutorial.įirst, let's try the function by opening a text file.

The modes define how we can access a file and how we can manipulate its content. The open() function accepts two essential parameters: the file name and the mode the default mode is 'r', which opens the file for reading only. Python provides a built-in function that helps us open files in different modes.
