Some Theory
Types of data used for I/O:
- Text - '12345' as a sequence of unicode chars
- Binary - 12345 as a sequence of bytes of its binary equivalent
Hence there are 2 file types to deal with
- Text files - All program files are text files
- Binary Files - Images,music,video,exe files
How File I/O is done in most programming languages
- Open a file
- Read/Write data
- Close the file
Writing to a file
Creating and writing to a new text file in Python using file handling
Explanation
- The code opens a file named 'sample.txt' in write mode ('w'), which creates the file if it doesn't exist or overwrites it if it does
- It writes the string 'Hello World' to the newly created file using the write() method
- The file handle is explicitly closed using close() to ensure data is properly saved and system resources are released
- This approach demonstrates basic file creation and writing operations in Python programming
This code demonstrates how to write to a file and the consequences of attempting to write after closing it.
Explanation
- The code opens a file named 'sample.txt' in write mode, which creates the file if it does not exist or truncates it if it does.
- It writes the string 'Hello World' to the file.
- The file is then closed using
f.close(), which finalizes the write operation and releases the file resource. - An attempt to write 'Hello' after closing the file results in an error, as the file is no longer open for writing.
Output
This code demonstrates how to write multiline strings to a text file in Python.
Explanation
- Opens a file named 'sample1.txt' in write mode, creating the file if it does not exist.
- Writes the string 'Hello World' to the file.
- Writes a newline character followed by 'how are you?' to the file, allowing for multiline content.
- Closes the file to ensure all data is saved and resources are released.
This code snippet demonstrates how to create and write to a text file in Python.
Explanation
- Opens a file named 'sample.txt' in write mode, which creates the file if it does not exist or truncates it if it does.
- Writes the string 'Madhu Dadi' to the file.
- Closes the file to ensure that all data is flushed and resources are released properly.
This code demonstrates how to append text to a file in Python using append mode.
Explanation
- The code opens a file named 'sample1.txt' in append mode ('a'), allowing new content to be added without overwriting existing data.
- The
writemethod is used to add a new line containing the text 'I am fine' to the end of the file. - The newline character (
\n) ensures that the new text starts on a new line in the file. - Finally, the
closemethod is called to properly close the file and save changes, preventing data loss.
This code snippet writes a list of strings to a text file in Python.
Explanation
- A list
Lcontaining strings with newline characters is defined. - A file named 'sample.txt' is opened in write mode using the
openfunction. - The
writelinesmethod is called on the file objectfto write all strings from the listLto the file. - The file is closed using
f.close()to ensure that all data is properly saved and resources are released.
This code snippet demonstrates how to read the entire content of a text file in Python.
Explanation
- Opens a file named 'sample.txt' in read mode using the
open()function. - Reads the entire content of the file into the variable
susing theread()method. - Prints the content of the file to the console using the
print()function. - Closes the file to free up system resources with the
close()method.
Output
This code snippet demonstrates how to read a specific number of characters from a text file in Python.
Explanation
- Opens a file named 'sample.txt' in read mode.
- Reads the first 10 characters from the file and stores them in the variable
s. - Prints the content of
sto the console. - Closes the file to free up system resources after reading.
Output
This code snippet demonstrates how to read lines from a text file in Python.
Explanation
- The code opens a file named 'sample.txt' in read mode using the
open()function. - It reads and prints the first line of the file with
f.readline(). - The second call to
f.readline()reads and prints the second line of the file. - Finally, the file is closed using
f.close()to free up system resources.
Output
Reading specific lines from a text file using the readline() method in Python
Explanation
- Opens a text file named 'sample.txt' in read mode to access its contents
- Uses readline() method to read and print the first line of the file, with end='' to prevent double newlines
- Calls readline() again to read and print the second line of the file
- Closes the file twice, though the second close operation is redundant and unnecessary
- Demonstrates sequential line reading from files using the built-in readline() function
Output
This code reads and prints each line from a text file until the end is reached.
Explanation
- Opens a file named 'sample.txt' in read mode.
- Continuously reads one line at a time using
readline()until an empty string indicates the end of the file. - Prints each line to the console without adding extra newlines due to the
end=''parameter. - Closes the file after reading to free up system resources.
- Note: The
f.close()is called twice, which is unnecessary and should be corrected.
Output
This code reads and prints all lines from a text file named 'sample.txt'.
Explanation
- The
openfunction is used to open 'sample.txt' in read mode ('r'). - The
readlinesmethod reads all lines from the file and returns them as a list. - The
printfunction outputs the list of lines to the console. - The
closemethod is called to properly close the file after reading, preventing potential resource leaks.
Output
Using Context Manager (With)
- It's a good idea to close a file after usage as it will free up the resources
- If we dont close it, garbage collector would close it
- with keyword closes the file as soon as the usage is over
Writing data to a file using a context manager in Python
Explanation
- The
withstatement is used to open a file, ensuring proper acquisition and release of resources. - The file 'sample1.txt' is opened in write mode ('w'), which creates the file if it does not exist or truncates it if it does.
- The variable
facts as a file object that allows interaction with the opened file. - The
writemethod is called on the file object to write the string 'Madhu Dadi' into the file. - Once the block under
withis exited, the file is automatically closed, preventing resource leaks.
Writing a string to a file in Python using the write method
Explanation
- The
f.write()method is used to write a specified string to an open file. - In this case, the string 'Hey, its closed already' is being written to the file referenced by
f. - The file must be opened in a writable mode (e.g., 'w' or 'a') for this operation to succeed.
- If the file is not open or is opened in a read-only mode, this operation will raise an error.
- After writing, it's good practice to close the file to ensure all data is flushed and resources are released.
Output
This code snippet demonstrates how to read the contents of a text file in Python.
Explanation
- The
withstatement is used to open the filesample.txtin read mode ('r'), ensuring proper resource management. - The file object
fis created, allowing access to the file's contents. - The
f.read()method reads the entire content of the file and returns it as a string. - The
print()function outputs the contents of the file to the console. - Using
withautomatically closes the file after the block of code is executed, preventing potential file leaks.
Output
This code snippet reads the first 10 characters from a text file named 'sample.txt'.
Explanation
- The
withstatement is used to open the file 'sample.txt' in read mode, ensuring proper resource management. - The
openfunction returns a file object, which is assigned to the variablef. - The
read(10)method reads the first 10 characters from the file and prints them to the console. - This approach is useful for quickly accessing a specific portion of the file without loading the entire content into memory.
Output
Reading a file in chunks of 10 characters using Python's file handling
Explanation
- The code opens a file named 'sample.txt' in read mode.
- It reads and prints the first 10 characters of the file using
f.read(10). - The second call to
f.read(10)reads the next 10 characters from the current file position. - This demonstrates how to sequentially read specific portions of a file without loading the entire content into memory.
Output
Efficiently writing a large list of strings to a text file in Python
Explanation
- Creates a list
big_Lcontaining the string 'hello world ' repeated 1000 times. - Opens a file named 'big.txt' in write mode using a context manager, ensuring proper file handling.
- Uses the
writelines()method to write all elements of the listbig_Lto the file in one operation, improving performance. - This approach is memory efficient for handling large datasets by avoiding multiple write calls.
Efficiently reading and processing a large text file in chunks
Explanation
- Opens a file named 'big.txt' in read mode using a context manager to ensure proper resource management.
- Defines a variable
chunk_sizeset to 100, which determines the number of characters to read at a time. - Uses a while loop to continuously read from the file until no more characters are left, checking the length of the read output.
- Prints the read chunk followed by '***' to separate outputs visually, but reads the next chunk without printing it, effectively skipping it.
- The approach allows for handling large files without loading the entire content into memory at once.
Output
Reading a specific number of characters from a file and checking the current position in Python
Explanation
- The code opens a file named 'sample.txt' in read mode using a context manager, ensuring proper resource management.
- It reads the first 10 characters from the file and prints them to the console.
- The
tell()method is called to retrieve the current position of the file pointer, which is printed next, indicating that it is at the 10th index after the read operation.
Output
Reading and tracking the position in a text file using Python's file handling methods
Explanation
- Opens a file named 'sample.txt' in read mode using a context manager, ensuring proper resource management.
- Reads the first 10 characters from the file and prints them to the console.
- Uses the
tell()method to display the current position of the file pointer, which is at the 10th index after the first read operation. - Reads the next 10 characters from the file and prints them, continuing from the last read position.
Output
Understanding file reading and position tracking in Python using seek and tell functions
Explanation
- The code opens a file named 'sample.txt' in read mode using a context manager, ensuring proper resource management.
- It reads the first 10 characters of the file and prints them to the console.
- The
tell()method is called to retrieve the current position of the file pointer, which will be at the 10th index after the read operation. - The
seek(0)method resets the file pointer back to the beginning of the file. - Finally, it reads and prints the first 10 characters again, demonstrating how the pointer's position affects the output.
Output
Demonstrating file reading and cursor manipulation in Python
Explanation
- Opens a file named 'sample.txt' in read mode using a context manager to ensure proper resource management.
- Reads and prints the first 10 characters from the file, moving the cursor to the 10th index.
- Uses the
tell()method to display the current position of the cursor, which is at the 10th index. - Calls the
seek(15)method to reposition the cursor to the 15th index in the file. - Reads and prints the next 10 characters starting from the new cursor position.
Output
Writing multiple strings to a file in Python using a context manager
Explanation
- The code opens a file named 'sample.txt' in write mode, which creates the file if it doesn't exist or truncates it if it does.
- It uses a context manager (
withstatement) to ensure the file is properly closed after writing, even if an error occurs. - Two strings, 'Hello' and 'Madhu', are written sequentially to the file without any newline characters in between.
- The file will contain the text "HelloMadhu" after the execution of this code.
This code demonstrates how to overwrite the beginning of a file after writing to it.
Explanation
- The code opens a file named 'sample.txt' in write mode, which creates the file if it does not exist or truncates it if it does.
- It writes the string 'Hello' to the file, which occupies the first five bytes.
- The
seek(0)method is then called to move the file pointer back to the start of the file. - After seeking, the code writes 'X', which overwrites the first byte of the file, resulting in the final content being 'Xllo'.
- This demonstrates how file pointers can be manipulated to modify specific parts of a file after initial writes.
Problems with working in text mode
- can't work with binary files like images
- not good for other data types like int/float/list/tuples
This code attempts to read a binary file but uses the wrong mode for opening it.
Explanation
- The code opens a file named 'Screenshot.png' using the 'r' mode, which is intended for reading text files.
- Since 'Screenshot.png' is a binary file, it should be opened in binary mode by using 'rb' instead of 'r'.
- Using the incorrect mode can lead to errors or unexpected behavior when reading binary data.
- The
f.read()method is called to read the contents of the file, but it will not function correctly due to the mode mismatch.
Output
Reading a binary file in Python to display its contents
Explanation
- The code opens a binary file named 'Screenshot.png' in read mode using the 'rb' flag, which is essential for handling non-text files.
- The
withstatement ensures that the file is properly closed after its contents are read, preventing resource leaks. - The
print(f.read())statement reads the entire content of the file and outputs it to the console, which may not be human-readable for binary files. - This approach is useful for handling images, audio, or other binary data formats in Python.
Output
This code snippet demonstrates how to copy a binary file in Python.
Explanation
- The code opens an existing binary file named 'Screenshot.png' in read-binary mode (
'rb'). - It creates a new binary file named 'Screenshot_copy.png' in write-binary mode (
'wb'). - The
read()method reads the entire content of the source file. - The
write()method writes the read content into the new file, effectively creating a copy of the original binary file. - The use of
withstatements ensures that both files are properly closed after their operations are completed.
Writing an integer to a text file in Python using a context manager
Explanation
- The code opens a file named 'sample.txt' in write mode, creating the file if it doesn't exist.
- A context manager (
withstatement) is used to ensure the file is properly closed after writing. - The integer
5is written to the file, but this will raise aTypeErrorsincewrite()expects a string. - To fix the error, the integer should be converted to a string using
str(5)before writing. - This snippet demonstrates basic file handling and the importance of data type compatibility in file operations.
Output
Writing a string to a file in Python using a context manager
Explanation
- The code opens a file named 'sample.txt' in write mode ('w'), which creates the file if it does not exist or truncates it if it does.
- The
withstatement ensures that the file is properly closed after the block of code is executed, even if an error occurs. - The
f.write('5')method writes the string '5' to the file; note that file operations in Python require strings, so non-string data types must be converted. - This snippet demonstrates basic file handling in Python, emphasizing the importance of using context managers for resource management.
This code attempts to read a file and perform an arithmetic operation on its content.
Explanation
- The code opens a file named 'sample.txt' in read mode using a context manager, ensuring proper resource management.
- It reads the entire content of the file into memory with
f.read(). - The code attempts to add the integer
5to the string returned byf.read(), which will raise a TypeError since these data types are incompatible. - This snippet illustrates the importance of type compatibility when performing operations in Python.
Output
Reading an integer from a file and performing arithmetic operations in Python
Explanation
- Opens a file named 'sample.txt' in read mode using a context manager to ensure proper resource management.
- Reads the entire content of the file and converts it to an integer using the
int()function. - Adds 5 to the integer value obtained from the file.
- The result of the addition is printed to the console.
- Assumes that the content of 'sample.txt' is a valid integer; otherwise, it may raise a
ValueError.
Output
Writing a dictionary to a text file in Python
Explanation
- A dictionary
dis created with keys 'name', 'age', and 'gender' containing respective values. - The
withstatement is used to open a file named 'sample.txt' in write mode, ensuring proper resource management. - The
writemethod attempts to write the dictionaryddirectly to the file, which will raise an error sincedneeds to be converted to a string format first.
Output
Writing a dictionary to a text file in Python
Explanation
- A dictionary
dis created containing keys for 'name', 'age', and 'gender' with corresponding values. - The
withstatement is used to open a file named 'sample.txt' in write mode, ensuring proper resource management. - The
str()function converts the dictionary into a string format before writing it to the file. - The file is automatically closed after the block of code is executed, preventing potential file corruption or data loss.
Reading and type checking file content using context manager in Python
Explanation
- Opens a text file named 'sample.txt' in read mode using a context manager for proper file handling
- Reads the entire file content and prints it to the console
- Attempts to read the file content again and prints its data type, which will show <class 'str'> since file reading returns string data
- The context manager ensures the file is properly closed after reading, even if an error occurs during execution
- This demonstrates basic file I/O operations and Python's built-in string type identification
Output
Reading a text file and converting its contents into a dictionary in Python
Explanation
- The code opens a file named 'sample.txt' in read mode using a context manager, ensuring proper resource management.
- It reads the entire content of the file into a string using
f.read(). - The string is then converted into a dictionary using the
dict()constructor, which attempts to interpret the string as key-value pairs. - A comment indicates that this method is not suitable for storing complex data formats, implying limitations in the data structure.
Output
Serialization and Deserialization
- Serialization - process of converting python data types to JSON format
- Deserialization - process of converting JSON to python data types
What is JSON? (JavaScript Object Notation)
This code snippet demonstrates how to serialize a Python list into a JSON file using the json module.
Explanation
- The
jsonmodule is imported to enable JSON serialization and deserialization. - A list
Lcontaining integers is defined. - The
with open()statement opens a file named 'demo.json' in write mode, ensuring proper file handling. - The
json.dump()function is used to write the listLinto the opened JSON file, converting it into a JSON format.
This code snippet demonstrates how to write a Python dictionary to a JSON file.
Explanation
- A dictionary
dis created with keys 'name', 'age', and 'gender' containing respective values. - The
with openstatement is used to open a file named 'demo.json' in write mode. - The
json.dump()function is called to serialize the dictionarydand write it to the opened file in JSON format. - This approach ensures that the file is properly closed after writing, even if an error occurs during the operation.
This code snippet demonstrates how to deserialize JSON data from a file in Python.
Explanation
- Imports the
jsonmodule to handle JSON data. - Opens a file named 'demo.json' in read mode using a context manager to ensure proper file handling.
- Loads the JSON content from the file into a Python dictionary using
json.load(). - Prints the deserialized dictionary to the console for verification.
- Displays the type of the deserialized object, confirming it is a dictionary.
Output
This code demonstrates how to serialize a tuple to JSON format and save it to a file.
Explanation
- The code imports the
jsonmodule to handle JSON serialization and deserialization. - A tuple
tcontaining integers is defined. - The
withstatement opens a file named 'demo.json' in write mode, ensuring proper resource management. - The
json.dump()function is used to serialize the tuple and write it to the file, converting the tuple into a JSON-compatible format (a list). - The comment indicates that the tuple is saved as a list in the JSON file, reflecting the conversion process.
This code snippet reads and prints the contents of a JSON file in Python.
Explanation
- The
with open('demo.json', 'r') as f:statement opens the filedemo.jsonin read mode, ensuring proper resource management. - The
json.load(f)function parses the JSON data from the file objectfinto a Python dictionary or list, depending on the structure of the JSON. - The
print()function outputs the parsed data to the console, allowing the user to see the contents of the JSON file. - Using the
withstatement automatically closes the file after the block of code is executed, preventing potential file handling issues.
Output
This code snippet demonstrates how to serialize a nested dictionary to a JSON file in Python.
Explanation
- The code defines a nested dictionary
dcontaining a student's name and their corresponding marks. - It uses the
jsonmodule to convert the dictionary into a JSON formatted string. - The
with openstatement opens a file named 'demo.json' in write mode, ensuring proper resource management. - The
json.dump()function writes the serialized dictionary to the specified file, allowing for easy data storage and retrieval.
This code snippet reads and prints the contents of a JSON file in Python.
Explanation
- The
with open('demo.json', 'r') as f:statement opens the filedemo.jsonin read mode, ensuring proper resource management. - The
json.load(f)function parses the JSON data from the file objectfinto a Python dictionary or list, depending on the structure of the JSON. - The
print()function outputs the parsed data to the console, allowing the user to see the contents of the JSON file. - Using the
withstatement automatically closes the file after the block of code is executed, preventing potential file handling issues.
Output
Serializing and Deserializing custom objects
This code defines a Person class to encapsulate personal attributes and their initialization.
Explanation
- The
Personclass is initialized with four attributes: first name (fname), last name (lname), age, and gender. - The
__init__method assigns the provided values to the instance variables of the class. - This structure allows for easy creation and management of person objects with specific attributes.
- The comment suggests a format for displaying the person's information, indicating how to present the data in a readable manner.
Creating an instance of a Person class with specific attributes
Explanation
- The code initializes a new object of the
Personclass, assigning it to the variableperson. - It passes four parameters to the constructor: first name ('Madhu'), last name ('Dadi'), age (33), and gender ('male').
- This instance can now be used to access or manipulate the attributes and methods defined in the
Personclass. - The
Personclass is expected to handle these attributes, likely storing them for further use in the program.
Writing a Python object to a JSON file using the json module
Explanation
- The code imports the
jsonmodule, which is used for working with JSON data in Python. - It opens a file named 'demo.json' in write mode, allowing data to be written to it.
- The
json.dump()function attempts to serialize thepersonobject and write it to the opened file. - A comment indicates that the
personobject cannot be serialized, suggesting it may not be a JSON-compatible type.
Output
Serialize a custom object to JSON using a custom formatting function
Explanation
- The code imports the
jsonmodule to handle JSON serialization. - A function
show_objectis defined to format aPersonobject into a string representation, including first name, last name, age, and gender. - The
isinstancecheck ensures that the inputpersonis indeed an instance of thePersonclass before formatting. - The
with openstatement opens a file named 'demo.json' in write mode, ensuring proper file handling. - The
json.dumpfunction writes thepersonobject to the file, usingshow_objectto format it if it's not serializable by default.
Serialize a custom object to JSON format using a custom function in Python
Explanation
- The code defines a function
show_objectthat converts aPersonobject into a dictionary format containing the person's name, age, and gender. - It checks if the input
personis an instance of thePersonclass before proceeding with the conversion. - The
json.dumpfunction is used to write the serialized data to a file named 'demo.json', utilizing theshow_objectfunction to handle the custom object serialization. - The
defaultparameter injson.dumpallows for specifying a custom serialization function for non-serializable objects. - The
indentparameter is set to 4, which formats the JSON output to be more readable with indentation.
This code snippet demonstrates how to read and deserialize JSON data from a file in Python.
Explanation
- The
jsonmodule is imported to handle JSON data parsing. - The
openfunction is used to open a file named 'demo.json' in read mode. - The
json.load()function reads the JSON data from the file and deserializes it into a Python dictionary. - The deserialized data is printed to the console, followed by its type, which confirms that it is a dictionary.
Output
Pickling
Pickling is the process whereby a Python object hierarchy is converted into a byte stream, and unpickling is the inverse operation, whereby a byte stream (from a binary file or bytes-like object) is converted back into an object hierarchy.
This Python class defines a Person with attributes and a method to display their information.
Explanation
- The
Personclass is initialized with two attributes:nameandage. - The
__init__method sets the instance variablesself.nameandself.agebased on the provided arguments. - The
display_infomethod prints a formatted string that includes the person's name and age. - This class can be instantiated to create multiple Person objects, each with unique attributes.
- The method can be called on any instance to output the person's information to the console.
Creating an instance of the Person class with specified attributes
Explanation
- This line of code initializes a new object
pof thePersonclass. - The constructor of the
Personclass is called with two arguments: a string'Madhu'representing the name and an integer30representing the age. - The attributes of the
Personinstancepwill be set to the provided values, allowing access top.nameandp.age. - This is a common practice in object-oriented programming to create and manage entities with specific properties.
This code snippet demonstrates how to serialize a Python object using the pickle module.
Explanation
- The
picklemodule is imported to enable object serialization and deserialization in Python. - A file named 'person.pkl' is opened in write-binary mode (
'wb'), which allows for binary data to be written to the file. - The
pickle.dump()function is called to serialize the objectpand write it to the opened filef. - This process converts the Python object into a byte stream, making it easy to save and transfer.
Loading and displaying a Python object from a pickle file
Explanation
- The code imports the
picklemodule, which is used for serializing and deserializing Python objects. - It opens a file named 'person.pkl' in binary read mode ('rb') to load the pickled object.
- The
pickle.load()function reads the contents of the file and reconstructs the original Python object, which is stored in the variablep. - The object
pis then printed to the console, displaying its representation. - Finally, the method
display_info()is called on the objectp, which presumably outputs additional details about the object.
Output
Pickle Vs Json
- Pickle lets the user to store data in binary format. JSON lets the user store data in a human-readable text format.
Q-1: Write a function get_final_line(filename), which takes filename as input and return final line of the file.
Note: You can choose any file of your choice.
Retrieve the last line of a specified text file in Python.
Explanation
- The function
get_final_linetakes a single argument,filename, which is the path to the text file. - It initializes an empty string
final_lineto store the most recent line read from the file. - A for loop iterates through each line in the file opened in read mode, updating
final_linewith the current line on each iteration. - After the loop completes, the function returns the last line read from the file.
- The function is called with "sample.txt" as the argument, which will return the last line of that specific file.
Output
###Q-2: Read through a text file, line by line. Use a dict to keep track of how many times each vowel (a, e, i, o, and u) appears in the file. Print the resulting tabulation -- dictionary.
Count the occurrences of vowels in a text file using a dictionary in Python
Explanation
- Defines a function
vowel_count_tablethat takes a filename as an argument. - Initializes a list of vowels and creates a dictionary
dto store the count of each vowel, starting at zero. - Opens the specified file and iterates through each line and character to check if it is a vowel.
- Increments the count for each vowel found in the dictionary.
- Returns the dictionary containing the total counts of each vowel after processing the entire file.
Output
###Q-3: Create a text file (using an editor, not necessarily Python) containing two tab separated columns, with each column containing a number. Then use Python to read through the file you’ve created. For each line, multiply each first number by the second and include it in the file in third column. In last add a line Total, by summing the value of third column
Input File example: That you need to create
Output File Example:
This code writes and processes data in a text file to calculate products and a total sum.
Explanation
- The code creates a file named "q3.txt" and writes pairs of odd numbers and their subsequent even numbers from 1 to 10, each on a new line.
- It then reads the contents of the file, splits each line into two numbers, and calculates the product of these numbers.
- The products are written back to the same file along with the original numbers, and a total sum of all products is appended at the end.
- The use of
with openensures that files are properly closed after their block of code is executed, preventing potential file corruption. - The final output in the file includes each pair of numbers, their product, and the cumulative total of all products.
###Q-4: Create line wise reverse of a file
Write a function which takes two arguments: the names of the input file (to be read from) and the output file (which will be created).
For example, if a file looks like
then the output file will be
Notice: The newline remains at the end of the string, while the rest of the characters are all reversed.
This Python code reverses the lines of a text file and writes them to a new file.
Explanation
- The code defines a function
reverse_linesthat takes two parameters: the input file name and the output file name. - It opens the input file in read mode and the output file in write mode using a context manager to ensure proper file handling.
- For each line in the input file, it removes any trailing whitespace, reverses the line, and writes the reversed line to the output file followed by a newline character.
- The function is called with "sample.txt" as the input file and "sample_reversed.txt" as the output file, executing the line reversal process.
###Q-5: Create a Serialized dict of frequency of words in the file. And from given list of words, using serialized dict show word count.
- List of word will be given
Given String
Python script for counting words in text and retrieving specific word frequencies
Explanation
- The code processes a multi-line string containing Alice in Wonderland text to count occurrences of each word
- It converts all text to lowercase and splits by spaces to create individual words for counting
- A dictionary tracks word frequencies, incrementing counts when words repeat or initializing counts for new words
- The word frequency data is serialized to a file using pickle for persistent storage
- The script retrieves and displays counts for specified target words, defaulting to zero if words aren't found
Output
Q-6: Given a string calculate length of the string using recursion.
Example 1:
Input:
Output:
Example 2:
Input:
Output:
This recursive function calculates the length of a given string in Python.
Explanation
- The function
string_lengthtakes a stringsas input and checks if it is empty. - If the string is empty, it returns 0, indicating that the length is zero.
- If the string is not empty, it recursively calls itself with the substring
s[1:], effectively reducing the string size by one character each time. - The function adds 1 to the result of the recursive call, counting each character until the base case (empty string) is reached.
- The final output is the total length of the original string 'DataScience', which is 11.
Output
Q-7: Write a function that accepts two numbers and returns their greatest common divisior. Without using any loop
def gcd(int, int) => int
This code implements the Euclidean algorithm to find the greatest common divisor (GCD) of two numbers.
Explanation
- The function
gcdtakes two integers,aandb, as input parameters. - It checks if the two numbers are equal; if so, it returns the value of either number as the GCD.
- If
ais greater thanb, it recursively calls itself with the differencea-bandb. - If
bis greater thana, it recursively calls itself with the differenceb-aanda. - The function is called with the values 16 and 24, which will ultimately return 8, the GCD of the two numbers.
Output
Q-8: String Edit Distance
Use your recursive function to write a program that reads two strings from the user and displays the edit distance between them.
The edit distance between two strings is a measure of their similarity—the smaller the edit distance, the more similar the strings are with regard to the minimum number of insert, delete and substitute operations needed to transform one string into the other.
Consider the strings kitten and sitting. The first string can be transformed
into the second string with the following operations:
- Substitute the
kwith ans, - substitute the
ewith ani, - and insert a
gat the end of the string.
This is the smallest number of operations that can be performed to transform kitten into sitting. As a result, the edit distance is 3.
Write a recursive function that computes the edit distance between two strings.
Use the following algorithm:
Calculate the minimum edit distance between two strings using recursion
Explanation
- The function
editDistancecomputes the minimum number of operations required to transform one string into another. - It handles base cases where either string is empty, returning the length of the other string as the edit distance.
- The function recursively calculates three possible operations: deletion, insertion, and substitution, and adds a cost of 1 for substitution if the last characters of the strings differ.
- It returns the minimum value among the three computed distances, effectively finding the least costly transformation path.
Output
###Q-9: Run-Length Encoding
Run-length encoding is a simple data compression technique that can be effective when repeated values occur at adjacent positions within a list. Compression is achieved by replacing groups of repeated values with one copy of the value, followed by the number of times that the value should be repeated. For example, the list
would be compressed as ["A", 12, "B", 4, "A", 6, "B", 1].
Write a recursive function that implements the run-length compression technique described above. Your function will take a list or a string as its only parameter. It should return the run-length compressed list as its only result. Include a main program that reads a string from the user, compresses it, and displays the run-length encoded result.
This code implements a recursive run-length encoding algorithm for a string.
Explanation
- The function
runEncodetakes a stringsas input and returns a list representing the run-length encoding of the string. - It checks if the string is empty; if so, it returns an empty list.
- The function uses a while loop to count consecutive identical characters, starting from the second character.
- It creates a list
compressedthat contains the first character of the string and the count of consecutive occurrences. - The function then recursively calls itself with the remaining substring, concatenating the results to build the complete encoded list.
Output
###Q-10: Write a recursive function to convert a decimal to binary
This Python function converts a decimal number to its binary representation using recursion.
Explanation
- The function
decToBintakes an integerdecimalas input and checks if it is zero, returning "0" if true. - If the decimal number is not zero, it recursively calls itself with the decimal number right-shifted by one bit (
decimal >> 1), effectively dividing the number by 2. - The binary digit corresponding to the least significant bit is obtained using
str(decimal & 1), which appends either '0' or '1' to the result. - The recursion continues until the base case (decimal equals zero) is reached, building the binary string from the least significant bit to the most significant bit.
- Finally, calling
decToBin(decimal)withdecimalset to 5 will return the string "101", which is the binary representation of 5.
Output
Next in this series: Python Iterators & Generators: Practical Guide With Examples →

