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

Python Unit 4 Code Explain

The document outlines three Python programs: one for sorting words from a file into another file in lowercase, another for reversing each line of a file, and a third for counting characters, words, and lines in a file. Each program includes steps for file handling, error management, and processing the content. The examples demonstrate file creation, reading, writing, and displaying results.

Uploaded by

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

Python Unit 4 Code Explain

The document outlines three Python programs: one for sorting words from a file into another file in lowercase, another for reversing each line of a file, and a third for counting characters, words, and lines in a file. Each program includes steps for file handling, error management, and processing the content. The examples demonstrate file creation, reading, writing, and displaying results.

Uploaded by

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

[Link] a program to sort words in a file and put them in another file.

The output file


should have only lower-case words, so any upper-case words from source must be
lowered.
with open("[Link]", "w") as f:
[Link]("Apple banana Mango grape ORANGE")
print("[Link] created successfully!")
Explanation:
 "w" → Opens the file in write mode
 If [Link] does not exist → it will be created
 If it already exists → old content will be overwritten
 The text written into the file is:
Apple banana Mango grape ORANGE
 with open() automatically closes the file after writing
🔹 2. Define Function to Sort Words
def sort_words(input_file, output_file):
 Defines a function named sort_words
 Takes:
o input_file → file to read
o output_file → file to write sorted words
🔹 3. Error Handling
try:
 Used to handle errors safely
 Prevents program crash if file is missing
🔹 4. Read Words from Input File
with open(input_file, "r") as file:
words = [Link]().split()
Explanation:
 "r" → Read mode
 [Link]() → Reads entire content
 .split() → Splits text into list of words
After this line:
words = ['Apple', 'banana', 'Mango', 'grape', 'ORANGE']
🔹 5. Convert Words to Lowercase
lower_words = [[Link]() for word in words]
Explanation:
 List comprehension
 Converts all words to lowercase
 Makes sorting case-insensitive
Now:
lower_words = ['apple', 'banana', 'mango', 'grape', 'orange']
🔹 6. Sort Words Alphabetically
sorted_words = sorted(lower_words)
 sorted() sorts words in ascending (A → Z) order
Result:
['apple', 'banana', 'grape', 'mango', 'orange']
🔹 7. Write Sorted Words to Output File
with open(output_file, "w") as file:
for word in sorted_words:
[Link](word + "\n")
Explanation:
 Opens [Link] in write mode
 Writes each word on a new line
 "\n" → Adds new line
Output file content:
apple
banana
grape
mango
orange

with open("[Link]", "w") as f:


[Link]("Hello World\nPython Programming\nGoogle Colab")
print("Sample file created.")
Explanation:
 "w" → Opens file in write mode
 If file doesn’t exist → it is created
 If file exists → old content is overwritten
 \n → Creates a new line
File Content ([Link]):
Hello World
Python Programming
Google Colab
Output:
Sample file created.

19. Python program to print each line of a file in reverse order


Define Function to Reverse Each Line
with open("[Link]", "w") as f:
[Link]("Hello World\nPython Programming\nGoogle Colab")
print("Sample file created.")
[Link] reverse_lines(filename):
 Function named reverse_lines
 Takes filename as input parameter
🔹 3. Error Handling (try-except)
try:
 Used to prevent program crash
 Handles error if file does not exist
🔹 4. Open File in Read Mode
with open(filename, 'r') as file:
 'r' → Read mode
 with automatically closes file after use
🔹 5. Read File Line by Line
for line in file:
 Reads one line at a time
 First iteration: "Hello World\n"
 Second iteration: "Python Programming\n"
 Third iteration: "Google Colab"
🔹 6. Remove Newline and Reverse Line
reversed_line = [Link]()[::-1]
Explanation:
🔸 [Link]()
 Removes trailing spaces and \n
Example:
"Hello World\n" → "Hello World"
🔸 [::-1]
 Python slicing to reverse string
 Syntax: string[start:stop:step]
 -1 step → reverse direction
Example:
"Hello World" → "dlroW olleH"
🔹 7. Print Reversed Line
print(reversed_line)
🔹 8. Handle File Not Found Error
except FileNotFoundError:
print("Error: File not found.")
 If file doesn't exist → prints error message
🔹 9. Call the Function
reverse_lines("[Link]")
 Reads file
 Reverses each line
 Prints result
🔹 Final Output
dlroW olleH
gnimmargorP nohtyP
baloC elgooG

[Link] program to compute the number of characters, words and lines in a


file.
with open("[Link]", "w") as f:
[Link]("Hello World\nPython is Easy")

print("Sample file created.")


Explanation:
 "w" → Opens file in write mode
 Creates [Link] (or overwrites if already exists)
 \n → Moves to next line
File Content:
Hello World
Python is Easy
Output:
Sample file created.
🔹 2. Define Function to Count File Details
def count_file_details(filename):
 Defines a function
 Takes file name as input parameter
🔹 3. Error Handling (try-except)
try:
 Prevents program crash if file does not exist
🔹 4. Open and Read File
with open(filename, 'r') as file:
content = [Link]()
 'r' → Read mode
 [Link]() → Reads entire file as a single string
 Stored in variable content
Now content contains:
"Hello World\nPython is Easy"
🔹 5. Count Characters
characters = len(content)
 len() counts total characters
 Includes:
✔ Letters
✔ Spaces
✔ Newline character (\n)
For this file:
Hello World → 11 characters (including space)
\n → 1 character
Python is Easy → 14 characters (including spaces)
Total characters = 26
🔹 6. Count Words
words = len([Link]())
 split() divides text into words
 Default separator → space
 Creates list:
['Hello', 'World', 'Python', 'is', 'Easy']
Total words = 5
🔹 7. Count Lines
lines = [Link]('\n') + 1 if content else 0
Explanation:
 [Link]('\n') → Counts newline characters
 Each \n represents a line break
 Add +1 because:
o Lines = number of newline characters + 1
In this file:
 1 newline → 2 lines
So:
Number of lines = 2
If file is empty → lines = 0
🔹 8. Print Results
print("Number of characters:", characters)
print("Number of words:", words)
print("Number of lines:", lines)
Output:
Number of characters: 26
Number of words: 5
Number of lines: 2
🔹 9. Handle File Not Found
except FileNotFoundError:
print("Error: File not found.")
 If file does not exist → prints error message
🔹 10. Call the Function
count_file_details("[Link]")
 Executes the function
 Displays counts

You might also like