Thursday, January 29, 2026

Python 26

 File Handling

1.Introduction to File Handling

  •  File Handling allows a program to create, read, write, and manage files.
  • Using file handling, Python programs can read data, write data update data, and work with different file type like text and CSV.

File Handling allows a Python Program to:

Store data :Store data permanently

Read data :Read data from files

Write data: Write data to the files

Update data: Modify or append existing data in files

Handle various files: Work with files like text files, CSV files, logs,reports etc.


2.Basic File Operations

We can do various operations on a file.

First, we need to specify the mode to define what operation we want to perform on the file.

Syntax:

Open(filename,mode) 

Mode Description                     Example

"r"       Read(file must exist)       file = open('data.txt','r') Print(file.read())

"w"     Write(creates/overwrite)  file=open("data.txt","w") file.write("Hello CCIT")

"a"       Append                            file=open("data.txt","a") file.write("\nAWS")

"x"       Create new file                file=open("newfile.txt","x") file.write("New file created")

"rb"      Read binary                     file=open("image.jpg","rb") print(file.read())

"wb"     Write binary                    file=open('copy.bin","wb") file.write(b"binarydata")

"r+"      Read and write                file =open("data.txt" ,r+)  print(file.read()) file.write("\nNewcontext")

If you use with advantage is , you don't want explicitly mention file.close() 

Task1:

with open("data.txt","r") as file:
    print(file.read())

 If you are not using with need to mention file.close() mandatory   

Task2:

file =open('data.txt',"a")
file.write("\n We greate to Learning Full Stack")
#print(file.read())
file.close()

Best Practice to use with 

Task3: Seek advantage of position to tell

file =open('data.txt',"r+")
file.write("Data testing")
file.seek(0)
print(file.read())
file.close()

Output:

with out seek

PS C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day26> python app.py

 Learning Full Stackeate to Learning Full Stack.

with seek

PS C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day26> python app.py

Data testing Learning Full Stackeate to Learning Full Stack.

Task4: append +

file =open('data.txt',"a+")
file.write("CCIT Devops")
file.seek(0)
print(file.read())
file.close()

Output:

PS C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day26> python app.py

Data testing Learning Full Stackeate to Learning Full Stack.CCIT Devops

Task5: Override

file =open('data.txt',"w+")
file.write("AWS Devop Engineer")
file.seek(0)
print(file.read())
file.close()

Output:

PS C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day26> python app.py

AWS Devop Engineer

Task6:

file =open('Women.png',"rb")
print(file.read())
file.close()

Output:PS C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day26> python app.py

b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\xb8\x00\x00\x00\

3.Handling File Errors and Exceptions

File errors are common, each error has a specific exception.

We must handle them explicitly with standard exception-handling constructs(try-except-finally)

If the file is not available at the specified path a FileNotFoundError is raised

Task7: for try must should except block is required

try:
    with open('data.txt',"r") as file:
     print(file.read())
except FileNotFoundError:
   print("File does not exist")
finally:
   print("Execution completed.")

Output:

PS C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day26> python app.py

File does not exist

Execution completed.

 Task 7: File permission issue 

try:
    with open('data.txt',"r") as file:
     print(file.read())
except FileNotFoundError:
   print("File does not exist")
except PermissionError:
   print("You does not have permission")
except:
   print("There is problem")
finally:
   print("Execution completed.")

Output:PS C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day26> python app.py

You does not have permission

Execution completed.

4.Difference between read(),readline() and  and readliness()

read(),readline() and readlines() are the multiple file reading methods in python.

Type are for different needs based on the context 

read()

read the entire file content at once ,returns one single string 

Key points: Loads full file into memory, not suitable for large files

readline() Each time execute one line only not loaded full file

Task 8:

file= open('data.txt',"r")
print(file.readline())
print(file.readline())
print(file.readline())
file.close()

Output:PS C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day26> python app.py

AWS Devop Engineer

HTML Developer

Java Developer

Task 9: readlines it will gave list 
file= open('data.txt',"r")
print(file.readlines())
file.close()

Output:

PS C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day26> python app.py

['AWS Devop Engineer\n', 'HTML Developer\n', 'Java Developer\n', 'DotNet Developer']


Task10: tells the cursor where to start from ,first word "AWS Devop Engineer" start from 10th Position of the word.

data.txt (file)

AWS Devop Engineer

HTML Developer

Java Developer

DotNet Developer

file= open('data.txt',"a+")
file.seek(10)
print(file.tell())
print(file.read())
file.close()

Output:

PS C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day26> python app.py

10

Engineer

HTML Developer

Java Developer

DotNet Developer


Task: Next class

Reading and writing comma-separated values(CSV)

Navigation the File system.

--Thanks 




No comments:

Post a Comment