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