Skip to content
Cover image for: Python File Handling: Read, Write & More
#pythonBeginner

Python File Handling: Read, Write & More

May 7, 2026
Updated May 14, 2026
30 min read

AI Insights

Powered by GPT-4o-mini

Verified Context: python-file-handling-read-write-more

Complete guide to Python file handling for production applications. Learn all file modes (r, w, a, r+, rb, wb, ab), the with statement for guaranteed resource cleanup, reading techniques (read, readline, readlines, iteration), writing strategies, serialization with pickle for Python object persistence and JSON for cross-language data exchange, CSV file processing with the csv module, graceful error handling, and best practices for robust file I/O operations.

Quick Summary

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.

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
python

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.
python

Output

text

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.
python

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.
python

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 write method 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 close method is called to properly close the file and save changes, preventing data loss.
python

This code snippet writes a list of strings to a text file in Python.

Explanation

  • A list L containing strings with newline characters is defined.
  • A file named 'sample.txt' is opened in write mode using the open function.
  • The writelines method is called on the file object f to write all strings from the list L to the file.
  • The file is closed using f.close() to ensure that all data is properly saved and resources are released.
python

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 s using the read() 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.
python

Output

text

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 s to the console.
  • Closes the file to free up system resources after reading.
python

Output

text

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.
python

Output

text

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
python

Output

text

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.
python

Output

text

This code reads and prints all lines from a text file named 'sample.txt'.

Explanation

  • The open function is used to open 'sample.txt' in read mode ('r').
  • The readlines method reads all lines from the file and returns them as a list.
  • The print function outputs the list of lines to the console.
  • The close method is called to properly close the file after reading, preventing potential resource leaks.
python

Output

text

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 with statement 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 f acts as a file object that allows interaction with the opened file.
  • The write method is called on the file object to write the string 'Madhu Dadi' into the file.
  • Once the block under with is exited, the file is automatically closed, preventing resource leaks.
python

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.
python

Output

text

This code snippet demonstrates how to read the contents of a text file in Python.

Explanation

  • The with statement is used to open the file sample.txt in read mode ('r'), ensuring proper resource management.
  • The file object f is 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 with automatically closes the file after the block of code is executed, preventing potential file leaks.
python

Output

text

This code snippet reads the first 10 characters from a text file named 'sample.txt'.

Explanation

  • The with statement is used to open the file 'sample.txt' in read mode, ensuring proper resource management.
  • The open function returns a file object, which is assigned to the variable f.
  • 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.
python

Output

text

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.
python

Output

text

Efficiently writing a large list of strings to a text file in Python

Explanation

  • Creates a list big_L containing 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 list big_L to the file in one operation, improving performance.
  • This approach is memory efficient for handling large datasets by avoiding multiple write calls.
python

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_size set 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.
python

Output

text

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.
python

Output

text

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.
python

Output

text

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.
python

Output

text

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.
python

Output

text

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 (with statement) 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.
python

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.
python

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.
python

Output

text

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 with statement 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.
python

Output

text

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 with statements ensures that both files are properly closed after their operations are completed.
python

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 (with statement) is used to ensure the file is properly closed after writing.
  • The integer 5 is written to the file, but this will raise a TypeError since write() 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.
python

Output

text

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 with statement 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.
python

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 5 to the string returned by f.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.
python

Output

text

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.
python

Output

text

Writing a dictionary to a text file in Python

Explanation

  • A dictionary d is created with keys 'name', 'age', and 'gender' containing respective values.
  • The with statement is used to open a file named 'sample.txt' in write mode, ensuring proper resource management.
  • The write method attempts to write the dictionary d directly to the file, which will raise an error since d needs to be converted to a string format first.
python

Output

text

Writing a dictionary to a text file in Python

Explanation

  • A dictionary d is created containing keys for 'name', 'age', and 'gender' with corresponding values.
  • The with statement 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.
python

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
python

Output

text

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.
python

Output

text

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 json module is imported to enable JSON serialization and deserialization.
  • A list L containing 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 list L into the opened JSON file, converting it into a JSON format.
python

This code snippet demonstrates how to write a Python dictionary to a JSON file.

Explanation

  • A dictionary d is created with keys 'name', 'age', and 'gender' containing respective values.
  • The with open statement is used to open a file named 'demo.json' in write mode.
  • The json.dump() function is called to serialize the dictionary d and 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.
python

This code snippet demonstrates how to deserialize JSON data from a file in Python.

Explanation

  • Imports the json module 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.
python

Output

text

This code demonstrates how to serialize a tuple to JSON format and save it to a file.

Explanation

  • The code imports the json module to handle JSON serialization and deserialization.
  • A tuple t containing integers is defined.
  • The with statement 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.
python

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 file demo.json in read mode, ensuring proper resource management.
  • The json.load(f) function parses the JSON data from the file object f into 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 with statement automatically closes the file after the block of code is executed, preventing potential file handling issues.
python

Output

text

This code snippet demonstrates how to serialize a nested dictionary to a JSON file in Python.

Explanation

  • The code defines a nested dictionary d containing a student's name and their corresponding marks.
  • It uses the json module to convert the dictionary into a JSON formatted string.
  • The with open statement 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.
python

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 file demo.json in read mode, ensuring proper resource management.
  • The json.load(f) function parses the JSON data from the file object f into 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 with statement automatically closes the file after the block of code is executed, preventing potential file handling issues.
python

Output

text

Serializing and Deserializing custom objects

This code defines a Person class to encapsulate personal attributes and their initialization.

Explanation

  • The Person class 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.
python

Creating an instance of a Person class with specific attributes

Explanation

  • The code initializes a new object of the Person class, assigning it to the variable person.
  • 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 Person class.
  • The Person class is expected to handle these attributes, likely storing them for further use in the program.
python

Writing a Python object to a JSON file using the json module

Explanation

  • The code imports the json module, 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 the person object and write it to the opened file.
  • A comment indicates that the person object cannot be serialized, suggesting it may not be a JSON-compatible type.
python

Output

text

Serialize a custom object to JSON using a custom formatting function

Explanation

  • The code imports the json module to handle JSON serialization.
  • A function show_object is defined to format a Person object into a string representation, including first name, last name, age, and gender.
  • The isinstance check ensures that the input person is indeed an instance of the Person class before formatting.
  • The with open statement opens a file named 'demo.json' in write mode, ensuring proper file handling.
  • The json.dump function writes the person object to the file, using show_object to format it if it's not serializable by default.
python

Serialize a custom object to JSON format using a custom function in Python

Explanation

  • The code defines a function show_object that converts a Person object into a dictionary format containing the person's name, age, and gender.
  • It checks if the input person is an instance of the Person class before proceeding with the conversion.
  • The json.dump function is used to write the serialized data to a file named 'demo.json', utilizing the show_object function to handle the custom object serialization.
  • The default parameter in json.dump allows for specifying a custom serialization function for non-serializable objects.
  • The indent parameter is set to 4, which formats the JSON output to be more readable with indentation.
python

This code snippet demonstrates how to read and deserialize JSON data from a file in Python.

Explanation

  • The json module is imported to handle JSON data parsing.
  • The open function 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.
python

Output

text

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 Person class is initialized with two attributes: name and age.
  • The __init__ method sets the instance variables self.name and self.age based on the provided arguments.
  • The display_info method 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.
python

Creating an instance of the Person class with specified attributes

Explanation

  • This line of code initializes a new object p of the Person class.
  • The constructor of the Person class is called with two arguments: a string 'Madhu' representing the name and an integer 30 representing the age.
  • The attributes of the Person instance p will be set to the provided values, allowing access to p.name and p.age.
  • This is a common practice in object-oriented programming to create and manage entities with specific properties.
python

This code snippet demonstrates how to serialize a Python object using the pickle module.

Explanation

  • The pickle module 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 object p and write it to the opened file f.
  • This process converts the Python object into a byte stream, making it easy to save and transfer.
python

Loading and displaying a Python object from a pickle file

Explanation

  • The code imports the pickle module, 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 variable p.
  • The object p is then printed to the console, displaying its representation.
  • Finally, the method display_info() is called on the object p, which presumably outputs additional details about the object.
python

Output

text

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_line takes a single argument, filename, which is the path to the text file.
  • It initializes an empty string final_line to 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_line with 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.
python

Output

text

###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_table that takes a filename as an argument.
  • Initializes a list of vowels and creates a dictionary d to 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.
python

Output

text

###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

text

Output File Example:

text

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 open ensures 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.
python

###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

text

then the output file will be

text

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_lines that 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.
python

###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

text

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
python

Output

text

Q-6: Given a string calculate length of the string using recursion.

Example 1:

Input:

bash

Output:

bash

Example 2:

Input:

bash

Output:

bash

This recursive function calculates the length of a given string in Python.

Explanation

  • The function string_length takes a string s as 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.
python

Output

text

Q-7: Write a function that accepts two numbers and returns their greatest common divisior. Without using any loop

def gcd(int, int) => int

text

This code implements the Euclidean algorithm to find the greatest common divisor (GCD) of two numbers.

Explanation

  • The function gcd takes two integers, a and b, as input parameters.
  • It checks if the two numbers are equal; if so, it returns the value of either number as the GCD.
  • If a is greater than b, it recursively calls itself with the difference a-b and b.
  • If b is greater than a, it recursively calls itself with the difference b-a and a.
  • The function is called with the values 16 and 24, which will ultimately return 8, the GCD of the two numbers.
python

Output

text

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 k with an s,
  • substitute the e with an i,
  • and insert a g at 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:

text

Calculate the minimum edit distance between two strings using recursion

Explanation

  • The function editDistance computes 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.
python

Output

text

###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

text

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 runEncode takes a string s as 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 compressed that 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.
python

Output

text

###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 decToBin takes an integer decimal as 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) with decimal set to 5 will return the string "101", which is the binary representation of 5.
python

Output

text

Next in this series: Python Iterators & Generators: Practical Guide With Examples →

Frequently Asked Questions

The two types of data used for I/O are Text, which is a sequence of unicode characters, and Binary, which is a sequence of bytes of its binary equivalent.
Attempting to write to a file after it is closed results in a ValueError because the file is no longer open for writing.
To write multiline strings, you open a file in write mode, write the first line, and then use a newline character followed by the next line of text.
Opening a file in write mode 'w' truncates the file if it already exists, meaning it clears the file contents before writing new data.
Closing a file ensures that all data is properly saved and system resources are released.

How was this tutorial?

Python File Handling: Read, Write & More | Madhu Dadi