There might arise a situation where one needs to interact with external files with Python. Python provides inbuilt functions for creating, writing, and reading files. In this article, we will be discussing how to open an external file and close the same using Python. Show Opening a file in PythonThere are two types of files that can be handled in Python, normal text files and binary files (written in binary language, 0s, and 1s). Opening a file refers to getting the file ready either for reading or for writing. This can be done using theopen() function. This function returns a file object and takes two arguments, one that accepts the file name and another that accepts the mode(Access Mode). Note: The file should exist in the same
directory as the Python script, otherwise, the full address of the file should be written.
Example 1: Open and read a file using PythonIn this example, we will be opening a file to read-only. The initial file looks like the below: Code: Python3
Here we have opened the file and printed its content. Output: Hello Geek! This is a sample text file for the example. Example 2: Open and write in a file using PythonIn this example, we will be appending new content to the existing file. So the initial file looks like the below: Code: Python3
Now if you open the file you will see the below result, Output: Example 3: Open and overwrite a file using PythonIn this example, we will be overwriting the contents of the sample file with the below code: Code: Python3
The above code leads to the following result, Output: Example 4: Create a file if not exists in PythonThe path.touch() method of the pathlib module creates the file at the path specified in the path of the path.touch(). Python3
Output: Closing a file in PythonAs you notice, we have not closed any of the files that we operated on in the above examples. Though Python automatically closes a file
if the reference object of the file is allocated to another file, it is a standard practice to close an opened file as a closed file reduces the risk of being unwarrantedly modified or read. Example: Read and close the file using PythonPython3
Now if we try to perform any operation on a closed file like shown below it raises a ValueError: Python3
Output: ValueError: I/O operation on closed file. |