There are two file handling functions in python
- Open
- Close
The Open function is used for Reading, Writing and Creating files. The open function excepts two arguments. File name/location and the mode. The mode indicates what action is required. i.e Reading, Writing, Creating. It also specifies if you want the file output in text or binary format.
Modes in Python.
- r = open and read files in text format
- rb = open and read files in binary format
- r+ = opens the file for reading and writing
- w = opens the file for writing. it overwrites the file
- a = opens the file for editing and appending data
Close Function It is used to close the open file. It does not take any arguments.
Another way to open and close a file in python is the “with open function”
with open("file_name", "r") as file:It closes the file automatically.
To open a file in binary format. You need to specify that by adding the letter “b” to the particular mode. See below
open("file_name", rb)Let’s put File Handling into practice
file = open("file_name", mode = "r")
data = file.readline() #outputs the file contents in a single line
print(data)
file.close()Another way of doing this is shown below
with open("file_name", mode = "r") as file:
data = file.readline()
print(data)The “with open” function differs from the former because it is better at exception handling and also closed the file for you automatically.
READING FILES
- read()
prints the content of a file as a string that contains all of the characters. you can also pass an argument as an integer to specify the number of characters you want to print.
read(50) # prints the first 50 characters- readline()
returns a single line as a string. it prints out only the first line. you can also pass an argument as an integer to specify the number of characters you want to print.
readline(50)- readlines()
read the entire contents of a file and returns it in an ordered list