Created
August 1, 2025 09:02
-
-
Save craig552uk/e3815ebd6ce6e0622a121c32116cf8df to your computer and use it in GitHub Desktop.
Split File Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import sys | |
# split a file into multiple files 1200 lines each | |
def split_file(input_file, lines_per_file=1200): | |
if not os.path.isfile(input_file): | |
print(f"Error: The file {input_file} does not exist.") | |
return | |
with open(input_file, 'r') as file: | |
lines = file.readlines() | |
total_lines = len(lines) | |
num_files = (total_lines + lines_per_file - 1) // lines_per_file # Ceiling division | |
for i in range(num_files): | |
output_file = f"{input_file}_part{i + 1}.txt" | |
with open(output_file, 'w') as out_file: | |
start_index = i * lines_per_file | |
end_index = min(start_index + lines_per_file, total_lines) | |
out_file.writelines(lines[start_index:end_index]) | |
print(f"Created: {output_file}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment