The key function for working with files in Python is the open() function.¶
- The open() function takes two parameters; filename, and mode.
Types of Mode¶
- “r” – Read – Default value. Opens a file for reading, error if the file does not exist
- “w” – Write – Opens a file for writing, creates the file if it does not exist
- “a” – Append – Opens a file for appending, creates the file if it does not exist
- “r+” – Read + Write
- “w+” – Create + Read + Write (Previous Data Erase)
- “a+” – Create + Read + Write (Append Mode)
Open the file¶
- fo = open(“itronix.txt”)
- fo = open(“itronix.txt”,’r’)
In [1]:
fo = open('itronix.txt','r') #file is not present so it will give error
Write to file¶
- if file not exist it will create the file
In [2]:
fo=open('itronix.txt','w')
fo.write("Welcome to Python Tutorials")
fo.close()
Read from file¶
In [3]:
fo=open('itronix.txt','r')
data=fo.read()
print(data)
Read Only Parts of the File¶
In [4]:
fo=open('itronix.txt','r')
data=fo.read(7) #read first 7 characters
print(data)
Read Line¶
- You can return one line by using the readline() method:
In [5]:
fo=open('itronix.txt','r')
data=fo.readline()
print(data)
Read Lines¶
- You can return Line by Line in a List by using the readlines() method:
In [6]:
fo=open('itronix.txt','r')
data=fo.readlines()
print(data)
Loop through the file line by line:¶
In [7]:
fo=open('itronix.txt','r')
for x in fo:
print(x)
Write in Append Mode¶
In [8]:
fo=open('itronix.txt','a')
fo.write("Learn Python from MachineLearning.org.in")
fo.close()
In [9]:
fo=open('itronix.txt','r')
data=fo.read()
print(data)
Write+ Mode: Used for both read and write¶
In [10]:
fo=open('itronix.txt','w+')
fo.write("Welcome to Python Tutorials. ")
data=fo.read()
print(data)
fo.close()
Note: Data is written in file but it won’t read any single character because pointer is point at the end. so we need to move pointer to the starting postion with the help of seek() function
Seek(offset[, whence])¶
- offset − This is the position of the read/write pointer within the file.
- whence − This is optional and defaults to 0 which means absolute file positioning,
In [11]:
fo=open('itronix.txt','w+')
fo.write("Welcome to Python Tutorials. ")
fo.seek(0,0)
data=fo.read()
print(data)
fo.close()
Tell() : used to find the total characters in file from starting position to pointer current position¶
In [12]:
fo=open('itronix.txt','w+')
fo.write("Welcome to Python Tutorials. ")
Length = fo.tell()
print("Total Characters in File:",Length)
fo.close()