File Handling
File open
The key function for opening files in Python is open() function. The input parameters are filename and mode.
There are four different modes for opening a file:
- "r" - Read: Opens a file for reading. Returns an error if the file doesn't exist.
- "a" - Append: Opens a file for appending a file. File is created if it doesn't exist.
- "w" - Write: Opens a file for writing. File is created if it doesn't exist.
- "x" - Create: Create a file and write in it. Returns an error if the file exists.
There are two ways a file can be handled:
- "t" - text: Reads a file as a text file.
- "b" - byte: Reads a file as a byte file.
Syntax
To open a file, use the open()
function and specify the method of opening.
If the method is not specified, then read ("r") and text ("t") are taken as default.
Example 1
f = open("file.txt")
Example 2
f = open("file.txt", "rt")
Text file content
We are so happy that you are here. This is just a test file. To show how file handling in Python works.
Read file
The read()
method is used to read the file. First, open the file in read ("r") mode.
Example
f = open("demofile.txt", "r")
print(f.read())
Output
We are so happy that you are here. This is just a test file. To show how file handling in Python works.
Read lines
readline()
is used to read one line of the file.
Example
f = open("file.txt", "r")
print(f.readline())
Output
We are so happy that you are here.
If readline()
is used 2 times, then the first 2 lines will be read and so on.
Example
f = open("file.txt", "r")
print(f.readline())
print(f.readline())
Output
We are so happy that you are here.
This is just a test file.
Close File
Close the file after reading.
Example
f = open("file.txt", "r")
print(f.read())
f.close()
Output
We are so happy that you are here. This is just a test file. To show how file handling in Python works.