File Handling in Python
In this article, we will learn about python file operations.
More specifically, opening a file, reading a file from it, writing into it, closing it, and various file methods that you should be aware of.
In Python, a file operation takes place in the following order:
- open a file
- Read or write (perform operation)
- Close the file
1. Opening Files
It is important to mention that before reading or writing to a file, one should first open it using the inbuilt Python function ‘open()‘. The mode parameter specifies what type of access the application is going to perform.
You can either write the file name if name is unique, else you can write whole file path.
There are following modes for opening a file:
‘r’ – Read
Default value. Opens a file for reading, error if the file does not exist.
‘a’ – Append
Opens a file for appending, creates the file if it does not exist
‘w’ – Write
Opens a file for writing, creates the file if it does not exist.
‘x’ – Create
Creates the specified file, returns an error if the file exists.
2. Reading files
To read a file in Python, we must open the file in reading mode.
‘r’: This tells the file is in reading mode
Writing to Files in Python
Writing a string or sequence of bytes in done using the write() method.
This program will create a new file named newfile.txt in the current directory if it does not exist. If it does exist, it is overwritten.
3. Closing Files
It is done using close() method available in Python.
This method is not entirely safe. Let’s discuss safe approach for this.
Closing Files: Best way
A safer way is to use a try…finally block.
This way, we are guaranteeing that the file is properly closed even if an exception is raised that caused program flow to stop.