The random access memory is volatile and all its contents are lost once a program terminates. In order to persists the data forever, we use Files.
A file is data stored in a storage device. A python program can talk to the File by reading content from it and writing content to it.
![]() |
file |
Types of Files :
there are two types of files
1. Text files (.txt, .c, etc)
2. Binary files (.jpg, .bat, .dat, etc)
Python has a lot functions for reading, updating and deleting files.
Opening a file :
Python has a open() function for opening files. It takes 2 parameters: filename and mode.
open("this.txt", "r")
open is a built in function, this.txt is file name and r is mode of opening i.e reading mode.
Reading a file in python :
f=open("this.txt", "r") : open the file in read mode
tex=f.read() : read its content
print(tex) : print its content
f.close () : close the file
We can also specify the number of characters in read() function : f.read(2) : reads first 2 characters
other methods to read the file :
we can also use f.readline() function to read on full line at a time.
f.readline() : reads one line from the file
Modes of opening a file :
r : open for reading
w : open for writting
a : open for appending
+ : open for updating
'vb' : will open for read in binary mode
'vt' : will open for read in text mode
Writing files in Python :
In order to write to a file, we first open it in write or append mode. After which we use the python f.write() method to write to the file.
f=open("this.txt", "w")
f.write("This is nice") :can be called multiple times
f.close()
With Statement:
the best way to open and close th efile automatically is the with statement
with open("this.txt") as f:
f.read()
Don't need to write f.close() as it is done automatically.
Programs :
1. #files
# Use open function to read the content of a file!
# f = open('sample.txt', 'r')
f = open('sample.txt') # by default the mode is r
# data = f.read()
data = f.read(5) # reads first 5 characters from the file
print(data)
f.close()
2. #readline
f = open('sample.txt')
# read first line
data = f.readline()
print(data)
# Read second line
data = f.readline()
print(data)
# Read third line
data = f.readline()
print(data)
# Read fourth line... and so on...
data = f.readline()
print(data)
f.close()
3. #write file
f = open('another.txt', 'w')
f.write("I am writing")
f.close()
4. #with
with open('another.txt', 'r') as f:
a = f.read()
with open('another.txt', 'w') as f:
a = f.write("me")
print(a)