0% found this document useful (0 votes)
16 views4 pages

Python Exp 8 210

Uploaded by

isharawool1
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)
16 views4 pages

Python Exp 8 210

Uploaded by

isharawool1
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
You are on page 1/ 4

Basic File Handling (Creating & Writing)

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


file.write("Hello,Python File Handling!")
print('File created and written successfully!')

File created and written successfully!

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


file.write("Hello, Python!\n")
file.write("This is a text file.\n")
file.write("We are learning file handling.\n")
print('File written successfully!')

File written successfully!

name=input("Enter Name:")
age=input("Enter Age:")
with open("user_data.txt.txt","w") as file:
file.write("Name:"+name+"\n")
file.write("Age:"+age+"\n")
print('File written successfully!')

Enter Name:isha
Enter Age:19
File written successfully!

Reading from a File

#Reading an Entire File

with open("my_file.txt","r") as file:


content=file.read()
print(content)

Hello, Python!
This is a text file.
We are learning file handling.

#Reading Line by Line


with open("my_file.txt","r") as file:
line1=file.readline()
line2=file.readline()
print(line1)
print(line2)

Hello, Python!

This is a text file.


#Reading First N Lines
with open("my_file.txt","r") as file:
lines=file.readlines()
print(lines)

['Hello, Python!\n', 'This is a text file.\n', 'We are learning file


handling.\n']

Modifying File Content

#Appending Content to a File


with open("my_file.txt","a") as file:
file.write("Appending new content to the file!")
print('Content appended successfully!')

Content appended successfully!

#Counting Words in a File

with open("my_file.txt","r") as file:


content=file.read()
words=content.split()
word_count=len(words)
print("Word Count:",word_count)

Word Count: 18

#Searching for a Word in a File

with open("my_file.txt","r") as file:


content=file.read()
search_word=input("Enter word to be search:")
if search_word in content:
print("Word found!")
else:
print("Word not found!")

Enter word to be search:python


Word not found!

Working with Multiple Files

try:
with open("my_file.txt", "r") as source_file, open("copy_file.txt",
"w") as destination_file:
for line in source_file:
destination_file.write(line)
print("File copied successfully!")
except FileNotFoundError:
print("Source file not found.")
except Exception as e:
print(f"An error occurred: {e}")

File copied successfully!

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


file.write("Hello,Python File Handling!")
with open("file2.txt","w") as file:
file.write("Python from second file")
with open("file2.txt","r") as file:
file2content=file.read()
with open("file1.txt","r") as file:
file1content=file.read()
with open("merged_file.txt","w") as file:
file.write(file1content+"\n"+file2content)

print('File created and written successfully!')

File created and written successfully!

#Write a program that removes all blank lines from "my_file.txt" and
saves the updated content in "cleaned_file.txt".

with open("my_file.txt","r") as file:


lines=file.readlines()
with open("cleaned_file.txt","w") as file:
for line in lines:
if line.strip():
file.write(line)

Binary File Handling (Images & PDFs)

Copying an Image File

#Write a program that reads an image file ("photo.jpg") in binary mode


and creates a duplicate of it as "copy_photo.jpg".

with open("photo.jpg","rb") as file:


image_data=file.read()
with open("copy_photo.jpg","wb") as file:
file.write(image_data)

Reading a Binary File

#Write a program that opens "sample.pdf" in binary mode and prints the
first 50 bytes of its content.

with open("sample.pdf","rb") as file:


content=file.read(50)
print(content)

b'%PDF-1.5\r\n%\xb5\xb5\xb5\xb5\r\n1 0 obj\r\n<</Type/Catalog/Pages 2
'

Deleting & Exception Handling

#Write a Python script that checks if "delete_me.txt" exists. If it


does, delete the file and display "File deleted successfully.".
#If the file does not exist, display "File does not exist.".

import os
try:
if os.path.exists("delete_me.txt"):
os.remove("delete_me.txt")
print("File deleted successfully!")
else:
print("File does not exist.")
except Exception as e:
print

File does not exist.

You might also like