Files
Files
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.
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.
********
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]
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.
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())
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.
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.
*********************
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
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.
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
total = 0
# read and display all numbers from the file
for line in file:
number = int(line.strip())
total += number
print(number)
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.
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
print(count)
file.close()
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.
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:
def lines_count():
vowels = ['a', 'e', 'i', 'o', 'u']
file = open('zen.txt', 'r')
file.close()
This code is designed to read a file named 'zen.txt' and print out lines from the
file that start with a vowel.
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
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.
def last_digit_words():
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:
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())
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
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 :
def long_lines():
file = open("lines.txt", 'r')
for line in file:
words = line.split()
if len(words) >= 8:
print(line.strip())
file.close()
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:
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.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'.
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
dv