File handling in Python 3
Table of content
- File handling
- Open method
- Modes
- Reading a file
- Writing to a file
- Creating a new file
File Handling
We can handle different file handling operations in Python. General steps for file handling is open a file, do read/write/append operations on the file and close the file.
Open function
open(<file_name>,<mode>) : Open function takes two parameters filename and mode.
Modes
r : open a file for read
w : open a file for write
a : open a file for append
r+ : open a file for read and write
rb : open a file for binary read (media files)
wb : open a file for binary write
ab : open a file for binary append
rb+ : open a file for binary read and write
x : create new file
Reading a file
file.read() - read method reads the entire file content. Assume you have a demofile.txt with some content as below.
Read file by line
file.readline() - method reads the content of the file line by line. We can looping through the contents of the file and process them. Below explain we are print the contents to the console.
Writing to a file
file.write("appended text") - method is used to write to a file. The file is opened in either append or write mode.
Below example in append mode, which adds the new content to existing content of the file at the end.
The file is opened in write mode. It will overwrite the existing contents of the file.
Create a new file
To create new file, we can use the create mode x
Thank you folks. If you like this Python 3 post, please do checkout my other post on Django with Python 3 series