File Handling
What is File Handling in Python?
File handling in Python is the process of reading, writing and managing files on the computer’s file system using built-in functions and methods.
In Python, a file operation takes places in the following order:
1. Open a file
2. Read or write (perform operation)
3. Close the file
Opening Files
Python has a built-in open() function to open a file
You can either write the file name if name is unique, else you can write whole file path.
There are four different methods (modes) for opening a file:
“r” – Read
Default value. Opens a file for reading, error if the file does not exists.
“a” – Append
Opens a file for appending, creates the file if it does not exists.
“w” – Write
Opens a file for writing, creates the file if it does not exists.
“x” – Create
Creates the specified file, returns an error if the file exists.
Reading Files
To read a file in Python, we must open the file in reading mode.
‘r’ – it tells the file is in reading mode.
Writing Files in Python
Writing a string or sequence of bytes is done using the write() method.
‘r’ – it tells the file is in reading mode.
Closing Files
It is done using the close method available in Python.
Leave a Reply
Want to join the discussion?Feel free to contribute!