Python Files IO
Till now, we were taking the input from the console and writing it back to the console to interact with the user. Sometimes, it is not enough to only display the data on the console. The data to be displayed may be very large, and only a limited amount of data can be displayed on the console, and since the memory is volatile, it is impossible to recover the programmatically generated data again and again. However, if we need to do so, we may store it onto the local file system which is volatile and can be accessed every time. Here, comes the need of file handling. In this section of the tutorial, we will learn all about file handling in python including, creating a file, opening a file, closing a file, writing and appending the file, etc. Opening a filePython provides the open() function which accepts two arguments, file name and access mode in which the file is accessed. The function returns a file object which can be used to perform various operations like reading, writing, etc. The syntax to use the open() function is given below.
The files can be accessed using various modes like read, write, or append. The following are the details about the access mode to open a file.
Example
Output: <class '_io.TextIOWrapper'> file is opened successfully The close() methodOnce all the operations are done on the file, we must close it through our python script using the close() method. Any unwritten information gets destroyed once the close() method is called on a file object. We can perform any operation on the file externally in the file system is the file is opened in python, hence it is good practice to close the file once all the operations are done. The syntax to use the close() method is given below.
Consider the following example.
Example
Reading the fileTo read a file using the python script, the python provides us the read() method. The read() method reads a string from the file. It can read the data in the text as well as binary format. The syntax of the read() method is given below.
Here, the count is the number of bytes to be read from the file starting from the beginning of the file. If the count is not specified, then it may read the content of the file until the end. Consider the following example. Example
Output: <class 'str'> Hi, I am Read Lines of the filePython facilitates us to read the file line by line by using a function readline(). The readline() method reads the lines of the file from the beginning, i.e., if we use the readline() method two times, then we can get the first two lines of the file. Consider the following example which contains a function readline() that reads the first line of our file "file.txt" containing three lines. Example
Output: <class 'str'> Hi, I am the file and being used as Looping through the fileBy looping through the lines of the file, we can read the whole file. Example
Output: Hi, I am the file and being used as an example to read a file in python. Writing the fileTo write some text to a file, we need to open the file using the open method with one of the following access modes. a: It will append the existing file. The file pointer is at the end of the file. It creates a new file if no file exists. w: It will overwrite the file if any file exists. The file pointer is at the beginning of the file. Consider the following example. Example 1
Now, we can see that the content of the file is modified. File.txt:
Example 2
Now, we can check that all the previously written content of the file is overwritten with the new text we have passed. File.txt:
Creating a new fileThe new file can be created by using one of the following access modes with the function open(). x: it creates a new file with the specified name. It causes an error a file exists with the same name. a: It creates a new file with the specified name if no such file exists. It appends the content to the file if the file already exists with the specified name. w: It creates a new file with the specified name if no such file exists. It overwrites the existing file. Consider the following example. Example
Output: File created successfully Using with statement with filesThe with statement was introduced in python 2.5. The with statement is useful in the case of manipulating the files. The with statement is used in the scenario where a pair of statements is to be executed with a block of code in between. The syntax to open a file using with statement is given below.
The advantage of using with statement is that it provides the guarantee to close the file regardless of how the nested block exits. It is always suggestible to use the with statement in the case of file s because, if the break, return, or exception occurs in the nested block of code then it automatically closes the file. It doesn't let the file to be corrupted. Consider the following example. Example
Output: Python is the modern day language. It makes things so simple. File Pointer positionsPython provides the tell() method which is used to print the byte number at which the file pointer exists. Consider the following example. Example
Output: The filepointer is at byte : 0 After reading, the filepointer is at 26 Modifying file pointer positionIn the real world applications, sometimes we need to change the file pointer location externally since we may need to read or write the content at various locations. For this purpose, the python provides us the seek() method which enables us to modify the file pointer position externally. The syntax to use the seek() method is given below.
The seek() method accepts two parameters: offset: It refers to the new position of the file pointer within the file. from: It indicates the reference position from where the bytes are to be moved. If it is set to 0, the beginning of the file is used as the reference position. If it is set to 1, the current position of the file pointer is used as the reference position. If it is set to 2, the end of the file pointer is used as the reference position. Consider the following example. Example
Output: The filepointer is at byte : 0 After reading, the filepointer is at 10 Python os moduleThe os module provides us the functions that are involved in file processing operations like renaming, deleting, etc. Let's look at some of the os module functions. Renaming the fileThe os module provides us the rename() method which is used to rename the specified file to a new name. The syntax to use the rename() method is given below.
Example
Removing the fileThe os module provides us the remove() method which is used to remove the specified file. The syntax to use the remove() method is given below.
Example
Creating the new directoryThe mkdir() method is used to create the directories in the current working directory. The syntax to create the new directory is given below.
Example
Changing the current working directoryThe chdir() method is used to change the current working directory to a specified directory. The syntax to use the chdir() method is given below.
Example
The getcwd() methodThis method returns the current working directory. The syntax to use the getcwd() method is given below.
Example
Deleting directoryThe rmdir() method is used to delete the specified directory. The syntax to use the rmdir() method is given below.
Example
Writing python output to the filesIn python, there are the requirements to write the output of a python script to a file. The check_call() method of module subprocess is used to execute a python script and write the output of that script to a file. The following example contains two python scripts. The script file1.py executes the script file.py and writes its output to the text file output.txt file.py:
file.py:
Output: 50 -4 That temperature doesn't make sense! 212 The file related methodsThe file object provides the following methods to manipulate the files on various operating systems.
|