Python File HandlingIntroduction:In this tutorial, we are discussing Python file handling. Python supports the file-handling process. Till now, we were taking the input from the console and writing it back to the console to interact with the user. Users can easily handle the files, like read and write the files in Python. In another programming language, the file-handling process is lengthy and complicated. But we know Python is an easy programming language. So, like other things, file handling is also effortless and short in Python. 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 since the memory is volatile, it is impossible to recover the programmatically generated data again and again. The file handling plays an important role when the data needs to be stored permanently into the file. A file is a named location on disk to store related information. We can access the stored information (non-volatile) after the program termination. In Python, files are treated in two modes as text or binary. The file may be in the text or binary format, and each line of a file is ended with the special character like a comma (,) or a newline character. Python executes the code line by line. So, it works in one line and then asks the interpreter to start the new line again. This is a continuous process in Python. Hence, a file operation can be done in the following order.
Opening a fileA file operation starts with the file opening. At first, open the File then Python will start the operation. File opening is done with the open() function in Python. This function will accepts two arguments, file name and access mode in which the file is accessed. When we use the open() function, that time we must be specified the mode for which the File is opening. The function returns a file object which can be used to perform various operations like reading, writing, etc. Syntax: The syntax for opening a file in Python 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.
Let's look at the simple example to open a file named "file.txt" (stored in the same directory) in read mode and printing its content on the console. Program code for read mode: It is a read operation in Python. We open an existing file with the given code and then read it. The code is given below - Output: Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below - <class '_io.TextIOWrapper'> file is opened successfully In the above code, we have passed filename as a first argument and opened file in read mode as we mentioned r as the second argument. The fileptr holds the file object and if the file is opened successfully, it will execute the print statement Program code for Write Mode: It is a write operation in Python. We open an existing file using the given code and then write on it. The code is given below - Output: Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below - The close() MethodThe close method used to terminate the program. Once 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 using the file system which is the currently opened in Python; hence it is good practice to close the file once all the operations are done. Earlier use of the close() method can cause the of destroyed some information that you want to write in your File. The syntax to use the close() method is given below. Syntax The syntax for closing a file in Python is given below - Consider the following example. Program code for Closing Method: Here we write the program code for the closing method in Python. The code is given below - After closing the file, we cannot perform any operation in the file. The file needs to be properly closed. If any exception occurs while performing some operations in the file then the program terminates without closing the file. We should use the following method to overcome such type of problem. The with statementThe with statement was introduced in python 2.5. The with statement is useful in the case of manipulating the files. It is used in the scenario where a pair of statements is to be executed with a block of code in between. Syntax: The syntax of with statement of a file in Python 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 files because, if the break, return, or exception occurs in the nested block of code then it automatically closes the file, we don't need to write the close() function. It doesn't let the file to corrupt. Program code 1 for with statement: Here we write the program code for with statement in Python. The code is given below - Program code 2 for with statement: Here we write the program code for with statement in Python. The code is given below - Writing the fileTo write some text to a file, we need to open the file using the open method and then we can use the write method for writing in this File. If we want to open a file that does not exist in our system, it creates a new one. On the other hand, if the File exists, then erase the past content and add new content to this File. the It is done by the following access modes. w: It will overwrite the file if any file exists. The file pointer is at the beginning of the file. 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. Program code 1 for Write Method: Here we write the program code for write method in Python. The code is given below - Output: Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below - File2.txt Python is the modern programming language. It is done any kind of program in shortest way. We have opened the file in w mode. The file1.txt file doesn't exist, it created a new file and we have written the content in the file using the write() function Program code 2 for Write Method: Here we write the program code for write method in Python. The code is given below - Output: Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below - Hello coders Welcome to javaTpoint Program code 3 for Write Method: Here we write the program code for write method in Python. The code is given below - Output: Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below - Python is the modern day language. It makes things so simple. It is the fastest growing language Python has an easy syntax and user-friendly interaction. Snapshot of the file2.txt We can see that the content of the file is modified. We have opened the file in a mode and it appended the content in the existing file2.txt. To read a file using the Python script, the Python provides the read() method. The read() method reads a string from the file. It can read the data in the text as well as a binary format. Syntax: The syntax of read() method of a file in Python 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. Program code for read() Method: Here we write the program code for read() method in Python. The code is given below - Output: Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below - <class 'str'> Python is In the above code, we have read the content of file2.txt by using the read() function. We have passed count value as ten which means it will read the first ten characters from the file. If we use the following line, then it will print all content of the file. So, it only prints 'Python is'. For read the whole file contents, the code is given below - Output: Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below - Python is the modern-day language. It makes things so simple. It is the fastest-growing programming language Python has easy an syntax and user-friendly interaction. Read file through for loopWe can use read() method when we open the file. Read method is also done through the for loop. We can read the file using for loop. Consider the following example. Program code 1 for Read File using For Loop: Here we give an example of read file using for loop. The code is given below - Output: Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below - Python is the modern day language. It makes things so simple. Python has easy syntax and user-friendly interaction. Program code 2 for Read File using For Loop: Here we give an example of read file using for loop. The code is given below - Output: Line1: H Line2: e Line3: l Line4: l Line5: o Line6: Line7: C Line8: o Line9: d Line10: e Line11: r Line12: s Line13: Line14: J Line15: a Line16: v Line17: a Line18: T Line19: p Line20: o Line21: i Line22: n Line23: t Line24: Read Lines of the filePython facilitates to read the file line by line by using a function readline() method. 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 "file2.txt" containing three lines. Consider the following example. Here we give the example of reading the lines using the readline() function in Python. The code is given below - Output: Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below - Python is the modern day language. It makes things so simple. We called the readline() function two times that's why it read two lines from the file.That means, if you called readline() function n times in your program, then it read n number of lines from the file. This is the uses of readline() function in Python. Python provides also the readlines() method which is used for the reading lines. It returns the list of the lines till the end of file(EOF) is reached. Example 2:Here we give the example of reading the lines using the readline() function in Python. The code is given below - Output: Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below - ['Python is the modern day language.\n', 'It makes things so simple.\n', 'Python has easy syntax and user-friendly interaction.'] Example 3: Here we give the example of reading the lines using the readline() function in Python. The code is given below - Output: Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below - Line1: Hello Line2: Coders Line3: JavaTpoint Creating a new fileThe new file can be created by using one of the following access modes with the function open().The open() function used so many parameters. The syntax of it is given below - file = open(path_to_file, mode) x, a and w is the modes of open() function. The uses of these modes are given below - 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. Program code1 for Creating a new file: Here we give an example for creating a new file in Python. For creates a file, we have to used the open() method. The code is given below - Output: Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below - <_io.TextIOWrapper name='file2.txt' mode='x' encoding='cp1252'> File created successfully Program code2 for creating a new file: Here we give an example for creating a new file in Python. For creates a file, we have to use the open() method. Here we use try block for erase the errors. The code is given below - Output: Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below - The file is does not exist File Pointer positionsPython provides the tell() method which is used to print the byte number at which the file pointer currently exists. The tell() methods is return the position of read or write pointer in this file. The syntax of tell() method is given below - Program code1 for File Pointer Position: Here we give an example for how to find file pointer position in Python. Here we use tell() method and it is return byte number. The code is given below - Output: Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below - The filepointer is at byte : 0 After reading, the filepointer is at: 117 Program code2 for File Pointer Position: Here we give another example for how to find file pointer position in Python. Here we also use tell() method, which is return byte number. The code is given below - Output: Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below - The pointer position is: 0 Modifying file pointer positionIn 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. That means, using seek() method we can easily change the cursor in the file, from where we want to read or write a file. Syntax: The syntax for 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. Here we give the example of how to modifying the pointer position using seek() method in Python. The code is given below - Output: Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below - The filepointer is at byte : 0 After reading, the filepointer is at: 10 Python OS module:Renaming the fileThe Python os module enables interaction with the operating system. It comes from the Python standard utility module. The os module provides a portable way to use the operating system-dependent functionality in Python. The os module provides the functions that are involved in file processing operations like renaming, deleting, etc. It provides us the rename() method to rename the specified file to a new name. Using the rename() method, we can easily rename the existing File. This method has not any return value. The syntax to use the rename() method is given below. Syntax: The syntax of rename method in Python is given below - The first argument is the current file name and the second argument is the modified name. We can change the file name bypassing these two arguments. Program code 1 for rename() Method: Here we give an example of the renaming of the files using rename() method in Python. The current file name is file2.txt, and the new file name is file3.txt. The code is given below - Output: Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below - The above code renamed current file2.txt to file3.txt Program code 2 for rename() Method: Here we give an example of the renaming of the files using rename() method in Python. The current file name is the source, and the new file name is the destination. The code is given below - Removing the fileThe os module provides the remove() method which is used to remove the specified file. Syntax: The syntax of remove method is given below - Program code 1 for remove() method: Output: Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below - The file named file3.txt is deleted. Program code 2 for remove() Method: Here we give an example of removing a file using the remove() method in Python. The file name is file3.txt, which the remove() method deletes. Print the command "This file is not existed" if the File does not exist. The code is given below - Output: Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below - This file is not existed Creating the new directoryThe mkdir() method is used to create the directories in the current working directory.It creates dictionary in numeric mode. If the file already presents in the system, then it occurs error, which is known as FileExistsError in Python. The mkdir() method does not return any kind of value. The syntax to create the new directory is given below. Syntax: The syntax of mkdir() method in Python is given below - Output: Parameter: The syntax of mkdir() method in Python is given below - path - A path like object represent a path either bytes or the strings object. mode - Mode is represented by integer value, which means mode is created. If mode is not created then the default value will be 0o777. Its use is optional in mkdir() method. dir_fd - When the specified path is absolute, in that case dir_fd is ignored. Its use is optional in mkdir() method. Program code 1 for mkdir() Method: Here we give the example of mkdir() method by which we can create new dictionary in Python. The code is given below - Output: Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below - Create a new dictionary which is named new Program code 2 for mkdir() Method: Here we give the example of mkdir() method by which we can create new dictionary in Python. The code is given below - Output: Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below - [Error 20] File exists: '/D:/JavaTpoint' The getcwd() method:This method returns the current working directory which have absolute value. The getcwd() method returns the string value which represents the working dictionary in Python. In getcwd() method, do not require any parameter. The syntax to use the getcwd() method is given below. Syntax The syntax of getcwd() method in Python is given below - Program code 1 for getcwd() Method: Here we give the example of getcwd() method by which we can create new dictionary in Python. The code is given below - Output: Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below - 'C:\\Users\\DEVANSH SHARMA' Program code 2 for getcwd() Method: Here we give the example of getcwd() method by which we can create new dictionary in Python. The code is given below - Output: Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below - The working directory is: C:\\Users\\JavaTpoint Changing the current working directoryThe chdir() method is used to change the current working directory to a specified directory.The chdir() method takes a single argument for the new dictionary path. The chdir() method does not return any kind of value. Syntax The syntax of chdir() method is given below - Program code 1 for chdir() Method: Here we give the example of chdir() method by which we can change the current working dictionary into new dictionary in Python. The code is given below - Output: Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below - 'C:\\Users\\DEVANSH SHARMA\\Documents' Program code 2 for chdir() Method: Here we give another example of chdir() method by which we can change the current working dictionary into new dictionary in Python. The code is given below - Output: Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below - Currently working directory is changed Deleting directory:The rmdir() method is used to delete the specified directory. If the directory is not empty then there is occurs OSError. The rmdir() method does not have and kind of return value. Syntax Program code 1 for rmdir() Method: Here we give the example of rmdir() method by which we can delete a dictionary in Python. The code is given below - Output: Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below - It will remove the specified directory. Program code 2 for rmdir() Method: Here we give another example of rmdir() method by which we can delete a dictionary in Python. The code is given below - Output: Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below - The directory 'JavaTpoint' is successfully removed Output: Here we give the example of rmdir() method by which we can delete a dictionary in Python. Here we use try block for handle the error. The code is given below - Output: Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below - [Error 30] Permission denied: '/D:/User/Documents/JavaTpoint' The directory 'JavaTpoint' cannot be removed successfully Writing Python output to the files:In 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. Program code: file1.py file.py File Related Methods:The file object provides the following methods to manipulate the files on various operating systems. Here we discuss the method and their uses in Python.
Conclusion:In this tutorial, we briefly discussed the Python file handling. Users can easily handle the files, like read and write the files in Python. Here we discuss various methods in Python by which we can easily read, write, delete, or rename a file. We also give the program code of these methods for better understanding. Next TopicPython Modules |