0% found this document useful (0 votes)
4 views6 pages

File Handling in Python: Create, Read, Write

Uploaded by

xahiley611
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views6 pages

File Handling in Python: Create, Read, Write

Uploaded by

xahiley611
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Program – Create, Write, Read, Append & Using Different

Modes
# Program: Basic File Handling Operations

# 1. Create & Write (write mode "w")


file = open("[Link]", "w")
[Link]("Name: Aman\n")
[Link]("Roll: 101\n")
[Link]("Branch: MCA\n")
[Link]()
print("✔ File created and data written successfully.\n")

# 2. Append mode ("a") - add new content


file = open("[Link]", "a")
[Link]("\nSemester: 2")
[Link]()
print("✔ New data appended to file.\n")
# 3. Read file ("r")
file = open("[Link]", "r")
content = [Link]()
print(" File Contents:\n" + content)
[Link]()
# 4. Read line-by-line
print("\n Line-by-line read:")
file = open("[Link]", "r")
for line in file:
print([Link]())
[Link]()
Program – File Pointer (tell() and seek())
# Program: File Pointer Operations
file = open("[Link]", "w")
[Link]("ABCDEFGH")
[Link]()

file = open("[Link]", "r")


print("Initial pointer position:", [Link]())

[Link](3)
print("Pointer after reading 3 characters:", [Link]())

[Link](2) # reposition pointer


print("Pointer after seek(2):", [Link]())

[Link]()
Program – Renaming and Deleting Files
import os

# 1. Create a file and write


with open("[Link]", "w") as f:
[Link]("AKTU MCA File Handling Topics")

# 2. Rename the file


[Link]("[Link]", "[Link]")
print("✔ File renamed to '[Link]'.")

# 3. Delete the file


[Link]("[Link]")
print("✔ File '[Link]' deleted.")
Program – Binary File Handling (Image Copy)
# Program: Working with Binary Files
with open("[Link]", "rb") as source:
content = [Link]()

with open("[Link]", "wb") as dest:


[Link](content)

print("✔ Binary image copied successfully!")

You might also like