IKH

Write Read Data

  • We can write character data to the text files by using the following 2 methods.
  • write(str)
  • writelines(list of lines)

Example

Python
f=open("abcd.txt",'w') 
f.write("Durga\n") 
f.write("Software\n") 
f.write("Solutions\n") 
print("Data written to the file successfully") 
f.close()

Output

PowerShell
3

abcd.txt

  • Durga
  • Software
  • Solutions

Note

  • In the above program, data present in the file will be overridden everytime if we run the program. Instead of overriding if we want append operation then we should open the file as follows.
  • f = open(“abcd.txt”,”a”)

Example

Python
f=open("abcd.txt",'w') 
list=["sunny\n","bunny\n","vinny\n","chinny"] 
f.writelines(list) 
print("List of lines written to the file successfully") 
f.close() 

Output

PowerShell
3

abcd.txt

  • sunny
  • bunny
  • vinny
  • chinny

Note

  • while writing data by using write() methods, compulsory we have to provide line seperator(\n),otherwise total data should be written to a single line.

Reading Character Data from text files

  • We can read character data from text file by using the following read methods.
  • read() To read total data from the file
  • read(n)  To read ‘n’ characters from the file
  • readline() To read only one line
  • readlines() To read all lines into a list

Example

Python
To read total data from the file
f=open("abc.txt",'r') 
data=f.read() 
print(data) 
f.close() 
 
Output
sunny 
bunny 
chinny 
vinny

Output

PowerShell
7

Example

Python
To read only first 10 characters:
f=open("abc.txt",'r') 
data=f.read(10) 
print(data) 
f.close() 

Output
sunny 
bunn

Output

PowerShell
5

Example

Python
To read data line by line:
f=open("abc.txt",'r') 
line1=f.readline() 
print(line1,end='') 
line2=f.readline() 
print(line2,end='') 
line3=f.readline() 
print(line3,end='') 
f.close() 
 
Output
sunny 
bunny 
chinny 

Output

PowerShell
5

Example

Python
To read all lines into list:
f=open("abc.txt",'r') 
lines=f.readlines() 
for line in lines: 
print(line,end='') 
f.close() 
 
Output
sunny 
bunny 
chinny 
vinny

Output

PowerShell
6

Example

Python
f=open("abc.txt","r") 
print(f.read(3)) 
print(f.readline()) 
print(f.read(4)) 
print("Remaining data") 
print(f.read()) 
 
Output
sun 
ny 
 
bunn 
Remaining data
 y 
chinny 
vinny

Output

PowerShell
7
  • The with statement can be used while opening a file.We can use this to group file operation statements within a block.
  • The advantage of with statement is it will take care closing of file,after completing all operations automatically even in the case of exceptions also, and we are not required to close explicitly.

Example

Python
with open("abc.txt","w") as f: 
f.write("Durga\n") 
f.write("Software\n") 
f.write("Solutions\n") 
print("Is File Closed: ",f.closed) 
print("Is File Closed: ",f.closed) 
 
Output
Is File Closed: False 
Is File Closed: True

Output

PowerShell
5

Report an error