Professional Documents
Culture Documents
File is a container of data stored in secondary computer memory for repeated use.
Program System
File File
File
Data User
File File
File
Operations
File Mode decides the type of operations to be done on the file opened herewith.
Examples:
Note : open() is built-in function and is called directly where as close() is called through file object.
Text File Read and Write Methods:
read() → Read Entire file readline() → Read Entire line readlines() → Read All Lines
read(n) →Read Only n readline(n) → Read Only n From Entire file
Bytes / characters bytes/ Characters from a line
Ret. Type - String Ret. Type - String Ret. Type – List of Strings
writelines(list)
write(string) → Write a list of strings
→ Write a string to a file to a file
Program Output
file = open("temp.txt",'w') Enter the content to write in the file : My name is
out_str = input("Enter the content to write in the Sonam Dutta. I read in Class 12. I study 5
file : ") subjects. I live in Bangalore.
file.write(out_str)
file.close() # File is created with the above content
Program Output
file = open("temp.txt",'r') First 10 Bytes from file : My name is
in_str = file.read(10) # Read First 10 characters Rest of the contents from file : Sonam Dutta. I
print("First 10 Bytes from file : ", in_str) read in Class 12. I study 5 subjects. I live in
Bangalore.
in_str = file.read() # Read All contents of file
print("Rest of the contents from file : ", in_str)
file.close()
4. writelines()
Program Output
with open("temp.txt",'r') as file: Content to be overwritten in the file :
in_str = file.read() ['My name is Sonam Dutta\n', ' I read in
LS = in_str.split('.') Class 12\n', ' I study 5 subjects\n', ' I live
for index in range(len(LS)): in Bangalore\n', '\n\n']
LS[index] += '\n'
print("Content to be overwritten in the file : ", LS)
5. readlines()
Program Output
with open("temp.txt",'r') as file: Line 1 : My name is Sonam Dutta
LS = file.readlines() Line 2 : I read in Class 12
for index in range(len(LS)): Line 3 : I study 5 subjects
print("Line",index+1," : ",LS[index], end='') Line 4 : I live in Bangalore
Line 5 :
#’\n’ is delimiter while reading each line Line 6 :
Device / File
Example :
Program Output
import sys Hello Students #Input from keyboard
String = sys.stdin.read(10) #Read max 10 chars Output = Hello Stud # Normal Display
sys.stdout.write("\nOutput = "+String) No error!!! # Error Display
sys.stderr.write("\nNo error!!!")
_______