Updated March 27, 2023
Introduction to File Handling in Python
Python also provides support for file handling as it is one of the very important topics in all the programming languages as it is required in any of the web applications. A file is a fixed location on a disk to store some information; these are given a unique name and can be stored permanently in non-volatile memory. File handling in simple it means handling of files such as opening the file, reading, writing, and many other operations. Unlike other programming languages, Python treats files as text or binary. In this programming language, each line of the file ends with a special character known as EOL (End of the line) like comma (,) or newline character. In this article, we will see about file operations.
How does File Handling work in Python?
Now let us start with the key function for file handling: open () function, which takes two arguments and returns the file object.
Syntax:
open (filename, mode)
Parameters:
- Filename: As discussed earlier, when the file is created, it is given a name to locate it on the disk.
- Mode: It specifies in which mode the file must be; this is an optional parameter because by default Python will take it as in reading mode “r”.
Types of modes used in Python
They are, to read the file we have “r” mode and result in an error if the file doesn’t exist, to write to the file we have “w” mode it will overwrite the content if already it has any content else it will create a new file if no file is present, we have “ a” mode to append the present contents to the previous contents of the file, and the last mode is “x” which is for exclusive creation of the file which creates the specific file.
Some other modes are also used like, or the combinations of the above modes are also used sometimes as modes:
- “r+”: Which is meant for both reading a file and writing to file.
- “t”: Text mode
- “b”: Binary mode
Example #1
file = open("file.txt", 'r')
Output:
The above code is to open the file in reading mode, but it gives the error as the file does not exist.
Whenever the files are opened, and the operations are done on them, we need to close the file; else, the file will not release the resources to other files, which may lead to resource leakage, and the systems will slow down. To close the file close() function is used for the above example:
file = open("file.txt", 'r')
…..
file.close()
Now the next important operation is reading the file, which is done when we want to read the contents of the file and print it, so we use the read() function.
Example #2
file = open("file.txt", 'r')
print(file.read())
Output:
The above code also gives an error to as the file does not exist because it is in reading mode, so there is no such file for reading.
The next operation is writing to the file, which is done by the write() function, but here the mode will change to write mode “w”, and as usual, we need to close the file.
Example #3
file = open("file.txt", 'w')
file.write("Hello Educba")
file = open("file.txt", 'r')
print(file.read())
Output:
In the above example, to write something to the file, it must be opened in write mode “w”, then only we can write to the file by using the write() function. To read these written files, we must again call the read() function on the same file in reading mode “r” then;, we can print the output as the content written into the file.
Another important operation is appending, which will write to the file without overwriting; instead, it will append the present content to the previous content. In the write mode, we have to note that if the file already exists and has some content in it and again we open it in write mode, then the file’s previous contents will be overwritten. So if we don’t want the content to be overwritten, then we need to use the append() function instead of the write() function.
Example #4
file = open("file.txt", 'w')
file.write("Hello Educba")
file.close()
file = open("file.txt", 'a')
file.write(" Training Institute")
file.close()
file = open("file.txt", 'r')
print(file.read())
Output:
In the above example, we could see that the file which already had “Hello Educba” written to the file in write mode than when the same file was opened in append mode, then writing to the same file was just appending the content to the previous content in append mode “Training Institute” was written so the output resulted in the complete content consisting of both the contents before appending after appending mode that is “Hello Educba Training Institute”.
Conclusion
In this article, basic operations of file handling in Python have discussed in which Python allows you to read, write, append, delete, etc. We saw how the open() function is used for both creating and opening a file. Then we saw the parameters for this function which can use many different modes on files like reading “r”, write “w”, append “a”, binary “b”, text “t”, etc., and there are many different functions like read(), write(), close(), rename() renaming the files, remove() –to delete files,mkdir() –create directories in the current directory, chdir() to change the current directory, getcwd() –get the current working directory, etc.
Recommended Articles
This is a guide to File Handling in Python. Here we discuss how does File Handling work in Python along with Syntax, Parameters and respective examples. You can also go through our other related articles to learn more–