The open function and file objects

To open a file, you can use Python's built-in open() function:

file = open("<relative/path/to/file>", "<permission>")

The variable named file in the previous example is what the documentation calls a file object. A file object doesn't actually contain the contents of the file, rather it is used to access the file's location in memory and give the program permission to operate on the file. The file object is generally used as a parameter to other functions that read the data.

The first parameter of the open() function is a string containing the relative path from the directory in which the program is run to the file containing your data.

The second parameter is the permission, which is a string designating the level of permission that is granted to the program for working with a file. I will use two permissions in this book for file I/O:

  • The read permission, designated by the r character, allows the program to read, but not to modify the contents of the file
  • The write permission, designated by the w character, allows the program to write to the file and automatically erases the contents of any file that already exists with the specified file path
There's a good reason not to use the 'w' permission unless you really intend to write to a particular file. Typically, in file browsers, there are precautions to make sure you do not lose data accidentally. If you are about to delete a file, a dialogue might come up to confirm, or the file might be moved temporarily to a trash bin folder before being permanently deleted. When opening a file with the 'w' permission, Python will mercilessly overwrite any file that already exists with the file path specified. As such, it is always a good idea to double-check that you are opening your data to read with the 'r' position and back up your input and output data.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset