0% found this document useful (0 votes)
177 views21 pages

Files

The program defines a function to write 10 random numbers between 1-100 to a file. It imports the random module, opens the file in write mode, generates random integers in a loop using random.randint(), converts them to strings and writes each number to the file followed by a newline. It closes the file after writing all numbers.

Uploaded by

jincy
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)
177 views21 pages

Files

The program defines a function to write 10 random numbers between 1-100 to a file. It imports the random module, opens the file in write mode, generates random integers in a loop using random.randint(), converts them to strings and writes each number to the file followed by a newline. It closes the file after writing all numbers.

Uploaded by

jincy
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
You are on page 1/ 21

Write a python program to add text to a file and display the text in python.txt.

def read_file(file_name):
from itertools import islice
with open(file_name, "w") as myfile:
myfile.write("Python Exercises\n")
myfile.write("Python Tutorials")
txt = open(file_name)
print(txt.read())
read_file('python.txt')

1. def read_file(file_name):
 This line defines a function named read_file that takes one parameter,
file_name.
2. from itertools import islice
 This line imports the islice function from the itertools module. However, it is
not used in the provided code, so it seems unnecessary here.
3. with open(file_name, "w") as myfile:
 This line opens the file specified by the file_name parameter in write mode
("w"). The with statement is used here to ensure that the file is properly
closed after writing. The file is assigned the alias myfile within the scope of
the with block.
4. myfile.write("Python Exercises\n")
 This line writes the string "Python Exercises" followed by a newline
character ("\n") to the opened file.
5. myfile.write("Python Tutorials")
 This line writes the string "Python Tutorials" to the opened file.
6. txt = open(file_name)
 This line opens the file specified by file_name in the default read mode. The
file is assigned to the variable txt.
7. print(txt.read())
 This line reads the contents of the file, which was opened in the previous
line, and prints the content to the console.
8. read_file('python.txt')
 This line calls the read_file function with the argument 'python.txt',
effectively creating (or overwriting) a file named 'python.txt', writing the
specified lines to it, and then reading and printing its contents.

Note: It's important to mention that using "w" mode ( open(file_name, "w")) in the with open
statement will overwrite the existing file content. If you want to preserve the existing
content, you may consider using "a" mode ( open(file_name, "a")) for append mode or "r+"
mode (open(file_name, "r+")) for read and write mode.

***********
5. Write a python program to read a file, a.txt line by line.

def read_file(file_name):
with open(file_name) as f:
#Content_list is the list that contains the read lines.
content_list = f.readlines()
print(content_list)

read_file('a.txt')

This code is a Python function designed to read the content of a file and print the lines
of the file. It takes a filename as an argument and opens the file using a with statement,
which ensures that the file is properly closed after reading. It then reads the lines of the
file and prints them using the print statement.

Now, let's break down the code line by line:

1. def read_file(file_name):: This line defines a function named read_file that takes a
parameter file_name, representing the name of the file to be read.
2. with open(file_name) as f:: This line opens the specified file ( file_name) using the open
function. The with statement is used to ensure that the file is properly closed after
its suite finishes, even if an exception is raised during the execution.
3. content_list = f.readlines(): This line reads all the lines from the file using the readlines
method and stores them in a list named content_list.
4. print(content_list): Finally, this line prints the contents of content_list, which contains
the lines of the file.
So, when you call read_file('a.txt'), it will read the content of the file named 'a.txt' and
print the lines.

********

8. Write a python program to identify the longest words in a file, a.txt.

The output is:

Sample Answer:
def longest_word(file_name):
with open(file_name, 'r') as f:
words = f.read().split()
max_length = len(max(words, key=len))
return [word for word in words if len(word) == max_length]

print("The longest words is", longest_word('a.txt')))

This code defines a function longest_word that takes a file name as input, reads the
content of the file, and then returns a list of words that have the maximum length
among all the words in the file. The maximum length is determined by finding the
length of the longest word in the file.

Now, let's break down the code line by line:


1. def longest_word(file_name): - This line declares a function named longest_word that
takes a single parameter file_name.
2. with open(file_name, 'r') as f: - This line opens the file specified by file_name in read
mode ('r'). The with statement ensures that the file is properly closed after
reading.
3. words = f.read().split() - This line reads the entire content of the file using f.read()
and then splits it into a list of words using the split() method. By default, split()
separates words based on whitespace.
4. max_length = len(max(words, key=len)) - This line finds the length of the longest word
in the words list. The max function is used with the key parameter set to len
(length), so it compares the words based on their length.
5. return [word for word in words if len(word) == max_length] - This line returns a list
comprehension that filters out only the words with a length equal to max_length.
These are the longest words in the file.
6. print("The longest words is", longest_word('a.txt'))) - This line prints a message along
with the result of calling the longest_word function with the file name 'a.txt'. Note
that there's an extra closing parenthesis at the end, which should be removed to
avoid a syntax error.

To summarize, this code reads a file, identifies the longest words, and returns a list
containing those longest words.

9. Write a python program to calculate the frequency of a all the words in a file, a.txt.
from collections import Counter
def word_count(file_name):
with open(file_name) as f:
return Counter(f.read().split())

print("The total number of each words in the file :")


print(word_count("a.txt"))

This code is a Python script designed to count the occurrences of each word in a text
file. It utilizes the Counter class from the collections module to count the frequency of each
unique word in the file.

Now, let's break down the code line by line:


1. from collections import Counter : This line imports the Counter class from the collections
module. The Counter class is useful for counting the occurrences of elements in a
collection, such as a list.
2. def word_count(file_name):: This line defines a function named word_count that takes
a single parameter, file_name. This function will be used to count the occurrences
of each word in the specified file.
3. with open(file_name) as f:: This line opens the file specified by file_name in a with
statement. The with statement ensures that the file is properly closed after
reading its contents.
4. return Counter(f.read().split()) : This line reads the contents of the file using f.read(),
splits the content into a list of words using split(), and then applies the Counter
class to count the occurrences of each word. The result is a Counter object, which
is then returned by the function.
5. print("The total number of each words in the file :") : This line prints a message to the
console.
6. print(word_count("a.txt")) : This line calls the word_count function with the filename
"a.txt" and prints the result, which is a Counter object containing the word
frequencies in the specified file.

In summary, this script is a simple word frequency counter for a given text file. It reads
the file, counts the occurrences of each word, and prints the results.

*********************

11. Write a python program to test whether a specified file is exist.

import os.path
open('document.txt', 'w')
print(os.path.isfile('document.txt'))

This code snippet is intended to create an empty text file named "document.txt" and
then check if the file has been successfully created.
Now, let's break down the code line by line:

1. import os.path: This line imports the path module from the os library. This module
provides a way to interact with the filesystem, including checking the existence of
files.
2. open('document.txt', 'w'): This line attempts to open a file named "document.txt" in
write mode ( 'w'). If the file does not exist, it will be created. However, this line
does not store the opened file object in a variable, so you won't be able to
perform further operations on it.
3. print(os.path.isfile('document.txt')) : This line checks if the file "document.txt" exists
using the os.path.isfile() function. This function returns True if the file exists and is a
regular file, and False otherwise. The result is then printed to the console.

It's worth noting that if you want to create an empty file and also interact with it later,
you should open the file and store the file object in a variable. For example:

pythonCopy code
file_path = 'document.txt' with open (file_path, 'w' ) as file: # Perform operations on the file if needed
print (os.path.isfile(file_path))

This way, you have a reference ( file) to the opened file and can perform additional
operations like reading, writing, or closing the file.

Write a program that writes 10 random numbers to a file 'numbers.txt'. Each random number
should be in the range of 1 through 100. Solution

import random

# Open the file in write mode


file = open("numbers.txt", "w")

# Generate and write random numbers to the file


for i in range(10):
number = random.randint(1, 100)
file.write(str(number) + "\n")

# Close the file after writing


file.close()

This code is for generating and writing ten random integers between 1 and 100
(inclusive) to a file named "numbers.txt". Each generated number is written on a new
line in the file.

Now, let's break down the code line by line:

1. import random: Imports the random module, which is used to generate random
numbers.
2. file = open("numbers.txt", "w") : Opens the file named "numbers.txt" in write mode
("w"). If the file does not exist, it will be created. If it already exists, the existing
content will be overwritten.
3. for i in range(10):: A loop that iterates 10 times.
4. number = random.randint(1, 100): Generates a random integer between 1 and 100
(inclusive) and assigns it to the variable 'number'.
5. file.write(str(number) + "\n") : Writes the generated random number as a string to
the file, followed by a newline character ("\n") to move to the next line in the file.
6. file.close(): Closes the file after writing all 10 random numbers. It is important to
close the file to ensure that changes are saved and system resources are released.

So, the code generates 10 random integers, writes each one to the "numbers.txt" file on
a new line, and then closes the file.

2. Write a program that reads and display all of the numbers stored in the file numbers.txt
(created in question 1) and calculates their total. Solution

# open the file in read mode


file = open("numbers.txt", "r")

total = 0
# read and display all numbers from the file
for line in file:
number = int(line.strip())
total += number
print(number)

# close the file after reading


file.close()

print("Total:", total)

This Python code is designed to read a file named "numbers.txt" in read mode, extract
and display each number from the file, and finally, calculate and print the total sum of all
the numbers in the file.

Now, let's break down the code line by line:

1. file = open("numbers.txt", "r") : This line opens the file named "numbers.txt" in read
mode ("r"), and the file object is assigned to the variable file.
2. total = 0: Initializes a variable total to store the sum of numbers read from the file.
It starts with a value of 0.
3. for line in file:: This initiates a loop that iterates over each line in the file. It reads
the file line by line.
4. number = int(line.strip()) : Inside the loop, each line is stripped of leading and trailing
whitespaces using strip(), and then converted to an integer using int(). This
assumes that each line in the file contains a valid integer.
5. total += number: Adds the current number to the running total.
6. print(number): Prints the current number.
7. file.close(): Closes the file after reading all the lines. This is a good practice to free
up system resources.
8. print("Total:", total): Prints the total sum of all numbers read from the file.
In summary, the code reads a file containing numbers, converts each line to an integer,
prints the individual numbers, calculates their total sum, and finally prints the overall
sum.

3. Write a function, digit_count() in Python that counts and displays the number of digits in the
text file named 'sample.txt'. For example, if the content of 'sample.txt' is as follows :
The team achieved a milestone in 2023. They completed a multi-million-dollar project ahead of
schedule. Stakeholders were impressed with a 98% success rate.
The function should display the output as 6 Solution
def digit_count():
file = open('sample.txt', 'r')
content = file.read()
count = 0

for char in content:


if char.isdigit():
count += 1

print(count)

file.close()

# Call the function


digit_count()

This Python code is designed to read the content of a file named 'sample.txt'
and count the number of digits present in the file. It then prints the count of
digits to the console.

Now, let's go through the code line by line:


1. file = open('sample.txt', 'r') :
This line opens the file named 'sample.txt' in read-
only mode ('r') and assigns the file object to the variable named file.
2. content = file.read() : Reads the entire content of the file and stores it in the
variable named content.
3. count = 0: Initializes a variable named count to keep track of the number of
digits found in the file. It starts with a count of zero.
4. for char in content: : Iterates over each character in the content variable.
5. if char.isdigit():: Checks if the current character char is a digit using the isdigit()
method.
6. count += 1: If the current character is a digit, increments the count variable
by 1.
7. print(count) : Prints the final count of digits to the console.
8. file.close() : Closes the file to free up system resources.

The function digit_count() encapsulates this logic, and when called, it reads the
file, counts the digits, prints the count, and then closes the file.
4. Write a function lines_count() that reads lines from a text file named 'zen.txt' and displays the
lines that begin with any vowel. Assume the file contains the following text and already exists
on the computer's disk:

Beautiful is better than ugly.


Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.

The lines_count() function should display the output as:


Explicit is better than implicit.
Solution

def lines_count():
vowels = ['a', 'e', 'i', 'o', 'u']
file = open('zen.txt', 'r')

for line in file:


# remove trailing newline character
line = line.rstrip()
# Check if the line starts with any vowel
if line[0].lower() in vowels:
print(line)

file.close()

# Call the function


lines_count()

This code is designed to read a file named 'zen.txt' and print out lines from the
file that start with a vowel.

Now, let's break down the code line by line:

1. def lines_count():
 This defines a function named lines_count .
2. vowels = ['a', 'e', 'i', 'o', 'u']
 Creates a list vowels containing the lowercase vowels.
3. file = open('zen.txt', 'r')
 Opens the file named 'zen.txt' in read-only mode ('r') and assigns
it to the variable file.
4. for line in file:
 Iterates through each line in the file.
5. line = line.rstrip()
 Removes trailing newline characters from the current line.
6. if line[0].lower() in vowels:
 Checks if the lowercase first character of the line is in the vowels list.
7. print(line)
 If the condition is true, it prints the line.
8. file.close()
 Closes the file after reading.
9. lines_count()
 Calls the function to execute the defined functionality.

In summary, this code reads each line from the 'zen.txt' file, removes any
trailing newline characters, and prints lines that start with a vowel. The vowels
are determined by the vowels list.
5. Assume that the file 'notes.txt' containing some text and exists on the computer’s disk. Write
a program that display only those words from 'notes.txt' file whose length is more than seven.
Keep in mind that any punctuation marks at the beginning or end of a word should also be
considered as part of the word's length. Solution

file = open("notes.txt", "r")


content = file.read()

# Split the content into words


words = content.split()

# Display words with length more than seven characters


print("Words with length more than seven:")
for word in words:
if len(word) > 7:
print(word)

# close the file


file.close()
This code reads the contents of a file named "notes.txt," splits the content into words,
and then displays words with a length greater than seven characters. Let's break down
the code line by line:

1. file = open("notes.txt", "r"): Opens the file named "notes.txt" in read-only mode ("r")
and assigns the file object to the variable file.
2. content = file.read(): Reads the entire content of the file and stores it in the variable
content.
3. words = content.split(): Splits the content into a list of words. The split() method by
default splits on whitespace characters (spaces, tabs, and newlines).
4. print("Words with length more than seven:") : Prints a header indicating that the
following words have a length greater than seven characters.
5. for word in words:: Initiates a loop that iterates through each word in the words list.
6. if len(word) > 7:: Checks if the length of the current word is greater than seven.
7. print(word): If the condition in line 6 is met, it prints the word.
8. file.close(): Closes the file, releasing the resources associated with it.

In summary, this code is designed to read the content of a file, identify words with a
length greater than seven characters, and print those words.

6. Write a function last_digit_words() in Python to count the words ending with a digit in a text
file "notes.txt". For example, if the file content is as follows :

The Computer6 hums softly as I sit with a Book3 in hand, diving into a world of imagination.
Outside, my friends gather at House9 and I quickly grab my Pen2 to jot down the address.

The expected output should be:


Number of words ending with a digit are 4 Solution

def last_digit_words():

file = open("notes.txt", 'r')


content = file.read()
words = content.split()
count = 0

for word in words:


if word[-1].isdigit():
count += 1

print("Number of words ending with a digit are", count)


file.close()

last_digit_words()

This code is designed to count the number of words in a file ( notes.txt) that end
with a digit. Here's a line-by-line explanation:

1. file = open("notes.txt", 'r') :


This line opens the file named "notes.txt" in read-
only mode ('r') and assigns the file object to the variable file.
2. content = file.read() : Reads the entire content of the file and stores it in the
variable content.
3. words = content.split() : Splits the content into a list of words using the split()
method. By default, this method splits on whitespace.
4. count = 0: Initializes a variable count to keep track of the number of words
ending with a digit.
5. for word in words: : Iterates through each word in the list.
6. if word[-1].isdigit(): : Checks if the last character of the current word is a digit
using the isdigit() method. If true, it indicates that the word ends with a
digit.
7. count += 1: If the condition in the previous line is true, increments the
count by 1.
8. print("Number of words ending with a digit are", count) : Prints the total count of words
ending with a digit.
9. file.close() : Closes the file to free up system resources.
In summary, the code reads the content of a file, splits it into words, and
counts how many of those words end with a digit. The final count is then
printed.

7. Assume that a file 'names.txt' containing a series of names (as strings) exists on the
computer’s disk. Write a function, first_five() that displays only the first five lines of the file’s
contents. If the file contains less than five lines, it should display the file’s entire contents.
Solution

def first_five():
# Read the content of the file
file = open("names.txt", "r")
lines = file.readlines()

# Display the first five lines or the entire content if the file
print("First five lines of the file's contents:")
for line in lines[:5]:
print(line.rstrip())

# close the file


file.close()

# Call the function


first_five()

This code is designed to read the contents of a file named "names.txt" and display the
first five lines of the file's content. Let's break down the code line by line:

pythonCopy code
def first_five (): # Read the content of the file file = open ( "names.txt" , "r" ) lines = file.readlines()
1. The function first_five() is defined. This function reads the content of a file named
"names.txt" and displays the first five lines.
2. file = open("names.txt", "r"): Opens the file named "names.txt" in read mode ("r"). It
assigns the file object to the variable file.
3. lines = file.readlines() : Reads all the lines from the file and stores them in the lines
variable as a list.
pythonCopy code
# Display the first five lines or the entire content if the file print ( "First five lines of the file's contents:" ) for line in
lines[: 5 ]: print (line.rstrip())
4. The code then prints a message indicating that it will display the first five lines of
the file's contents.
5. for line in lines[:5]:: Iterates over the first five lines in the lines list.
6. print(line.rstrip()) : Prints each line after removing any trailing whitespaces (using
rstrip()).
pythonCopy code
# close the file file.close()
7. file.close(): Closes the file to free up system resources after reading its content.
pythonCopy code
# Call the function first_five()
8. Calls the first_five() function to execute the defined functionality.

In summary, this code defines a function to read and display the first five lines of the
content of a file named "names.txt". It opens the file, reads its content, prints the first
five lines, and then closes the file.

8. Write a Python program that reads a text file and prints its contents in reverse order (from
the last line to the first line). Solution

file = open(file_path, 'r')


lines = file.readlines()
rlines = reversed(lines)
for line in rlines:
print(line.rstrip())
file.close()
This Python code appears to read the contents of a file, reverse the order of its lines,
and then print each line without trailing whitespaces.

Now, let's break down the code line by line:

1. file = open(file_path, 'r') : This line opens a file specified by the file_path in read mode
('r') and assigns the file object to the variable file.
2. lines = file.readlines() : This line reads all the lines from the opened file and stores
them as a list of strings in the variable lines.
3. rlines = reversed(lines) : This line creates a new list called rlines that contains the lines
from lines but in reversed order. The reversed() function returns a reverse iterator.
4. for line in rlines:: This line initiates a loop that iterates over each line in the reversed
list rlines.
5. print(line.rstrip()) : This line prints each line after removing any trailing whitespaces
(including newline characters) using the rstrip() method.
6. file.close(): This line closes the file after processing its contents. It's essential to
close files after reading or writing to ensure that system resources are released.

In summary, this code reads a file, reverses the order of its lines, and then prints each
line without trailing whitespaces.

9. Write the definition of a Python function named long_lines( ) which reads the contents of a
text file named 'lines.txt' and displays those lines from the file which have at least 8 words in it.
For example, if the content of 'lines.txt' is as follows :

Flat is better than nested.


Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.

The output should be:


Special cases aren't special enough to break the rules. Solution

def long_lines():
file = open("lines.txt", 'r')
for line in file:
words = line.split()
if len(words) >= 8:
print(line.strip())
file.close()

# call the function


long_lines()

This code is designed to read a file named "lines.txt" and print out lines that contain
eight or more words. Here's an explanation of each line:

1. def long_lines():: This line defines a function named long_lines.


2. file = open("lines.txt", 'r'): It opens the file named "lines.txt" in read-only mode ('r')
and assigns the file object to the variable file.
3. for line in file:: This line starts a loop that iterates over each line in the file.
4. words = line.split(): It splits the current line into a list of words based on whitespace.
The split() method without any arguments splits the string at spaces.
5. if len(words) >= 8:: It checks whether the number of words in the line is greater than
or equal to 8.
6. print(line.strip()): If the line has 8 or more words, it prints the line (stripped of
leading and trailing whitespaces).
7. file.close(): This line closes the file after the loop has finished iterating through all
lines.
8. long_lines(): This line calls the function long_lines() to execute the code inside the
function.

In summary, this code reads a file, checks each line for the number of words, and prints
lines that contain eight or more words.

10. Assume that a file named 'feedback.txt' contains student feedback in the following format:
Positive: Saksham improved grades, more confident now.
Negative: Arav needs better time management for coursework.
Negative: Samar should work on communication in group activities.
Negative: Soham could benefit from asking more questions in class.
Positive: Sakshi excels academically, a great team player.

Write a Python function named feedback_analysis() to calculate and display the following
information:
Total feedbacks stored in the file.
Count of positive feedbacks.
Count of negative feedbacks. Solution

def feedback_analysis():
total = 0
positive = 0
negative = 0

file = open('feedback.txt', 'r')


for line in file:
total += 1
if line.startswith('Positive'):
positive += 1
elif line.startswith('Negative'):
negative += 1

file.close()
print("Total feedbacks stored in the file:", total)
print("Count of positive feedbacks:", positive)
print("Count of negative feedbacks:", negative)

# Calling function
feedback_analysis()

This code is for analyzing feedback stored in a file named 'feedback.txt'. It counts the
total number of feedbacks, as well as the number of positive and negative feedbacks.
The feedbacks are assumed to be stored in the file with each line starting either with
'Positive' or 'Negative'.

Now, let's break down the code line by line:

1. total = 0: Initialize a variable total to keep track of the total number of feedbacks.
2. positive = 0: Initialize a variable positive to keep track of the number of positive
feedbacks.
3. negative = 0: Initialize a variable negative to keep track of the number of negative
feedbacks.
4. file = open('feedback.txt', 'r') : Open the file named 'feedback.txt' in read mode ('r')
and assign the file object to the variable file.
5. for line in file:: Iterate over each line in the file.
6. total += 1: Increment the total count for each feedback.
7. if line.startswith('Positive'): : Check if the current line starts with the string 'Positive'.
8. positive += 1: If the line starts with 'Positive', increment the positive count.
9. elif line.startswith('Negative'): : Check if the current line starts with the string
'Negative'.
10. negative += 1: If the line starts with 'Negative', increment the negative count.
11. file.close(): Close the file to free up system resources.
12. print("Total feedbacks stored in the file:", total) : Print the total number of feedbacks.
13. print("Count of positive feedbacks:", positive) : Print the count of positive feedbacks.
14. print("Count of negative feedbacks:", negative) : Print the count of negative feedbacks.

The purpose of this code is to provide a summary of the feedback data, showing the
total number of feedbacks and the counts of positive and negative feedbacks.
11. Create a Python function make_copy() that reads a text file 'input.txt' and writes its contents
to a new file 'output.txt', capitalizing the first letter of each word. For example, if 'input.txt'
contains the following content:

"In the world of programming, there are no limits to what you can achieve. Aim high!"
The 'output.txt' should contain:
"In The World Of Programming, There Are No Limits To What You Can Achieve. Aim High!"
Solution

N = int(input("Enter a positive integer: "))


sum_reciprocals = 0.0

for num in range(1, N + 1):


sum_reciprocals += 1 / num

print("The sum of reciprocals from 1 to", N, "is:", "{:.2f}".format(sum_reciprocals))

dv

You might also like