0% found this document useful (0 votes)
14 views

Assignment 6

Assignment for oOT

Uploaded by

akshataharage
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)
14 views

Assignment 6

Assignment for oOT

Uploaded by

akshataharage
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/ 8

assignment-6

March 30, 2024

[5]: #1

# File Handling Script

# a. center()
def center_text(text, width):
return text.center(width)

# b. repr()
def repr_text(text):
return repr(text)

# c. rjust()
def rjust_text(text, width):
return text.rjust(width)

# d. ljust()
def ljust_text(text, width):
return text.ljust(width)

# e. zfill()
def zfill_number(number, width):
return str(number).zfill(width)

# f. format()
def format_text(text, width):
return "{:<{}}".format(text, width)

# g. read()
def read_file(filename):
with open(filename, 'r') as file:
return file.read()

# h. open()
def open_file(filename, mode):
return open(filename, mode)

1
# i. tell()
def tell_position(file):
return file.tell()

# j. seek()
def seek_position(file, offset, whence):
file.seek(offset, whence)

# m. format()
def format_string(string, *args, **kwargs):
return string.format(*args, **kwargs)

# Example Usage:
if __name__ == "__main__":
# Creating and writing to a file
with open("ex.txt", "w") as file:
file.write("This is an example text file.")

# Reading from a file


content = read_file("ex.txt")
print("Content of 'ex.txt':", content)

# Using string formatting functions


print("Centered text:", center_text("Hello", 20))
print("Repr of text:", repr_text("Hello"))
print("Right justified text:", rjust_text("Hello", 20))
print("Left justified text:", ljust_text("Hello", 20))
print("Zfilled number:", zfill_number(42, 6))
print("Formatted text:", format_text("Hello", 10))
print("Formatted string:", format_string("{}, {}!", "Hello", "world"))

# File operations
file = open_file("ex.txt", "r")
print("Current file position:", tell_position(file))
seek_position(file, 0, 0)
print("Seeking to the beginning of the file...")
print("Current file position:", tell_position(file))

Content of 'ex.txt': This is an example text file.


Centered text: Hello
Repr of text: 'Hello'
Right justified text: Hello
Left justified text: Hello
Zfilled number: 000042
Formatted text: Hello

2
Formatted string: Hello, world!
Current file position: 0
Seeking to the beginning of the file…
Current file position: 0

[6]: #2

import shutil

# Create a file and write some content


with open("source_file.txt", "w") as source_file:
source_file.write("This is the content of the source file.")

# Function to copy file


def copy_file(source, destination):
try:
shutil.copyfile(source, destination)
print(f"File copied successfully from '{source}' to '{destination}'.")
except FileNotFoundError:
print("Error: One or both of the files does not exist.")
except PermissionError:
print("Error: Permission denied to copy the file.")
except shutil.SameFileError:
print("Error: Source and destination represent the same file.")
except Exception as e:
print("Error:", e)

# Copy the file


copy_file("source_file.txt", "destination_file.txt")

File copied successfully from 'source_file.txt' to 'destination_file.txt'.

[7]: #3

import os

def copy_file_to_binary(source_filename, destination_filename):


try:
# Check if the source file exists
if not os.path.exists(source_filename):
print(f"The source file '{source_filename}' does not exist.")
return

# Open the source file in binary mode for reading


with open(source_filename, 'rb') as source_file:
# Read the contents of the source file
data = source_file.read()

3
# Check if the destination file already exists
if os.path.exists(destination_filename):
print(f"The destination file '{destination_filename}' already␣
↪exists. Overwriting...")

# Open the destination file in binary mode for writing


with open(destination_filename, 'wb') as destination_file:
# Write the contents of the source file into the destination␣
↪ file
destination_file.write(data)

print(f"File copied successfully from '{source_filename}' to␣


↪ '{destination_filename}'.")
except Exception as e:
print("An error occurred:", e)

# Example usage
source_file = "source_file.txt"
destination_file = "destination_file.bin"

copy_file_to_binary(source_file, destination_file)

File copied successfully from 'source_file.txt' to 'destination_file.bin'.

[8]: #4

def count_characters(text):
vowels = 0
consonants = 0
digits = 0
special_chars = 0

for char in text:


if char.isalpha():
if char.lower() in 'aeiou':
vowels += 1
else:
consonants += 1
elif char.isdigit():
digits += 1
else:
special_chars += 1

return vowels, consonants, digits, special_chars

def analyze_file(filename):

4
try:
with open(filename, 'r') as file:
content = file.read()
vowels, consonants, digits, special_chars =␣
↪count_characters(content)

print("Content of the file:")


print(content)
print("\nAnalysis of the content:")
print("Number of vowels:", vowels)
print("Number of consonants:", consonants)
print("Number of digits:", digits)
print("Number of special characters:", special_chars)
except FileNotFoundError:
print(f"The file '{filename}' does not exist.")
except Exception as e:
print("An error occurred:", e)

# Create a file and write some content to it


with open("example_file.txt", "w") as file:
file.write("Hello! This is an example file.\nIt contains some numbers like␣
↪123456789.\nAnd also some special characters like @#$%^&*.")

# Analyze the file


analyze_file("example_file.txt")

Content of the file:


Hello! This is an example file.
It contains some numbers like 123456789.
And also some special characters like @#$%^&*.

Analysis of the content:


Number of vowels: 33
Number of consonants: 48
Number of digits: 9
Number of special characters: 29

[9]: #5

def read_file_lines(filename):
lines = []
try:
with open(filename, 'r') as file:
for line in file:
lines.append(line.strip()) # Strip newline characters and␣
↪append to the list

except FileNotFoundError:
print(f"The file '{filename}' does not exist.")

5
except Exception as e:
print("An error occurred:", e)
return lines

# Example usage
filename = "example_file.txt"
lines_array = read_file_lines(filename)
print("Contents of the file stored in an array:")
for line in lines_array:
print(line)

Contents of the file stored in an array:


Hello! This is an example file.
It contains some numbers like 123456789.
And also some special characters like @#$%^&*.

[10]: #6

def read_file_content(filename):
content = ""
try:
with open(filename, 'r') as file:
for line in file:
content += line # Concatenate each line to the content variable
except FileNotFoundError:
print(f"The file '{filename}' does not exist.")
except Exception as e:
print("An error occurred:", e)
return content

# Example usage
filename = "example_file.txt"
file_content = read_file_content(filename)
print("Contents of the file stored in a variable:")
print(file_content)

Contents of the file stored in a variable:


Hello! This is an example file.
It contains some numbers like 123456789.
And also some special characters like @#$%^&*.

[11]: #7

def write_content_to_file(filename, content):


try:
with open(filename, 'w') as file:
file.write(content)

6
print(f"Content written to '{filename}' successfully.")
except Exception as e:
print("An error occurred while writing to the file:", e)

def copy_content(source_filename, destination_filename):


try:
with open(source_filename, 'r') as source_file:
content = source_file.read()
write_content_to_file(destination_filename, content)
except FileNotFoundError:
print(f"The source file '{source_filename}' does not exist.")
except Exception as e:
print("An error occurred while copying the content:", e)

def count_content_stats(filename):
try:
with open(filename, 'r') as file:
lines = file.readlines()
line_count = len(lines)
word_count = sum(len(line.split()) for line in lines)
space_count = sum(line.count(' ') for line in lines)
blank_line_count = sum(1 for line in lines if line.strip() == '')

result = f"Number of lines: {line_count}\nNumber of words:␣


↪{word_count}\nNumber of blank spaces: {space_count}\nNumber of blank lines:␣

↪{blank_line_count}"

with open("c.txt", 'w') as result_file:


result_file.write(result)
print(f"Statistics written to 'c.txt' successfully.")
except FileNotFoundError:
print(f"The file '{filename}' does not exist.")
except Exception as e:
print("An error occurred while counting content stats:", e)

# Getting user input for content of files


content_a = input("Enter the content for file 'a.txt': ")
content_b = input("Enter the content for file 'b.txt': ")

# Writing content to files a.txt and b.txt


write_content_to_file("a.txt", content_a)
write_content_to_file("b.txt", content_b)

# Copying content from a.txt to c.txt


copy_content("a.txt", "c.txt")

# Counting content statistics and writing to c.txt

7
count_content_stats("c.txt")

Enter the content for file 'a.txt': hello python


Enter the content for file 'b.txt': hello java
Content written to 'a.txt' successfully.
Content written to 'b.txt' successfully.
Content written to 'c.txt' successfully.
Statistics written to 'c.txt' successfully.

You might also like