File Divider - Python Programming Exercise

In this exercise, you will develop a Python program to divide a file (of any type) into smaller segments of a specified size. This exercise is perfect for practicing file handling, byte manipulation, and loops in Python. By implementing this program, you will gain hands-on experience in handling file operations, byte manipulation, and loops in Python. This exercise not only reinforces your understanding of file handling but also helps you develop efficient coding practices for managing user interactions.

 Category

Managing Files

 Exercise

File Divider

 Objective

Develop a Python program to divide a file (of any type) into smaller segments of a specified size. The program should accept the filename and the segment size as inputs. For example, it can be executed like this:

split myFile.exe 2000

If the file "myFile.exe" is 4500 bytes in size, the program would generate three new files: "myFile.exe.001" of 2000 bytes, "myFile.exe.002" also 2000 bytes long, and "myFile.exe.003" containing the remaining 500 bytes.

 Example Python Exercise

 Copy Python Code
# Python program to divide a file into smaller segments

def split_file(filename, segment_size):
    try:
        # Open the source file in binary mode
        with open(filename, 'rb') as file:
            # Get the total size of the file
            file_size = len(file.read())
            
            # Calculate the number of segments required
            num_segments = (file_size // segment_size) + (1 if file_size % segment_size != 0 else 0)
            
            # Move the file pointer to the beginning again for reading the contents
            file.seek(0)
            
            # Split the file into smaller parts
            for i in range(1, num_segments + 1):
                # Read the segment of the specified size
                segment_data = file.read(segment_size)
                
                # Generate the segment filename (e.g., "myFile.exe.001")
                segment_filename = f"{filename}.{i:03d}"
                
                # Write the segment data into the new file
                with open(segment_filename, 'wb') as segment_file:
                    segment_file.write(segment_data)
                
                print(f"Created {segment_filename} with {len(segment_data)} bytes.")
                
    except FileNotFoundError:
        print(f"Error: The file '{filename}' does not exist.")
    except Exception as e:
        print(f"Error: {str(e)}")

# Example usage
split_file("myFile.exe", 2000)

 Output

Created myFile.exe.001 with 2000 bytes.
Created myFile.exe.002 with 2000 bytes.
Created myFile.exe.003 with 500 bytes.

 Share this Python Exercise

 More Python Programming Exercises of Managing Files

Explore our set of Python Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of Python. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in Python.

  •  BMP File Encryption

    In this exercise, you will develop a Python program to encrypt or decrypt a BMP image file by swapping the "BM" signature in the first two bytes with "MB" and vice ve...

  •  CSV Data Converter

    In this exercise, you will develop a Python program to read a CSV file containing comma-separated values. This exercise is perfect for practicing file handling...

  •  File content comparer

    In this exercise, you will develop a Python program to compare two files (of any type) and determine if they are identical (i.e., have the same content). This exer...

  •  Show BMP on console

    In this exercise, you will develop a Python program to decode and display a Netpbm image file. This exercise is perfect for practicing file handling, string ma...

  •  Extract Text Information from a Binary File

    In this exercise, you will develop a Python program to extract only the alphabetic characters contained in a binary file and dump them into a separate file. This e...

  •  Dump

    In this exercise, you will develop a Python program to create a "dump" utility: a hex viewer that displays the contents of a file, with 16 bytes in each row and 24 ro...