You are on page 1of 4

FILE HANDLING

File is a container of data stored in secondary computer memory for repeated use.

Program System
File File
File
Data User
File File

1. Stores UNICODE characters only


Text 2. Every line ends with special EOL character
File 3. Internal translation required for R/W of EOL.
4. Slower operations for execution

1. Stores raw data only


Binary 2. No special character or no delimiter for each line
File 3. No internal character translation required
4. Very fast for R/W during execution

File
Operations

Open Close Read Write


File File File File

File open and close operations:


• open() creates a file object and a link to the file residing in secondary computer memory
for read or write or both.
• close() breaks the link between file object and the actual file stored in disk at the end of file
operations.
• flush() forcefully writes the content of Output Buffer to the attached file in disk.
close() implicitly calls flush() before its execution.

Method 1: file_object = open(file_name_with_path, mode)


<File manipulation>
file_object.close() #CLOSE IS MUST

Method 2: with open(file_name_with_path, mode) as file_object:


<File manipulation> # CLOSE NOT REQUIRED AT ALL
File Object / File Handle is an object (of class '_io.TextIOWrapper') which attaches itself to one file at
a time, stored in the hard disk for access. File is accessed through file handle during any operations on
that file during the program execution.

File Mode decides the type of operations to be done on the file opened herewith.

SL TEXT BINARY FILE Operations Remarks


NO FILE MODE
MODE
1 “r” “rb” Read only File must exist, otherwise raise I/O Error.
DEFAULT MODE
2 “w” “wb” Write only New file created if file not existent, otherwise
overwrite / truncate existing data.
3 “a” “ab” Append only New file created if file not existent, otherwise
new content added after existing data.
4 “r+” “r+b” or “rb+” Read + Write File must exist, otherwise raise I/O Error.
5 “w+” “w+b” or “wb+” Write + Read New file created if file not existent, otherwise
overwrite / truncate existing data.
6 “a+” “a+b” or “ab+” Append + Read New file created if file not existent, otherwise
new content added after existing data.

Examples:

1. try: 2. f = open("C:\\Sonam\\temp.txt", "w")


f = open("temp.txt") #Default mode read f.close()
print("File types is = ", type(f))
print("File address is = ", id(f)) Open file in write mode with Absolute path
f.close() # Must close manually starting with the Drive Name and nested folders
are separated by ‘\\’
except: #FileNotFoundError Exception 3. with open("temp.txt", "a") as f:
print("Error occurred!!! ") print("File Opened successfully")
#Automatic closure of file
Case 1: temp.txt does not exist
Output: Error occurred!!! Open file in append mode with Relative path
i.e. temp.txt is stored in the same folder as the
Case 2: temp.txt exists program file
Output:
File types is = <class '_io.TextIOWrapper'> 4. f = open(r"C:\Sonam\temp.txt", "r+")
File address is = 140263501191568 f.flush() # Flush writes buffer contents to file
f.close()

r → raw string i.e. no special meaning attached


to any character, so ‘\’

Note : open() is built-in function and is called directly where as close() is called through file object.
Text File Read and Write Methods:

Text File Read

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

Text File Read

writelines(list)
write(string) → Write a list of strings
→ Write a string to a file to a file

Sample Programs with Read/Write Functions


1. write():

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

2. read() and 3. readline()

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)

with open("temp.txt",'w') as file:


# Reuse same file handle with same file but different mode
file.writelines(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 :

Standard Input and Output Streams

Device / File

Standard Input Device: Standard Output Device: Standard Error Device:


stdin stdout stderr

Default Device : Keyboard Default Device: Monitor

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!!!")

_______

You might also like