Using python to split text files by line,
This example describes how to split text files by line in python. We will share this with you for your reference. The details are as follows:
Python scripts use shell commands to perform text operations. These commands greatly reduce the amount of code.
For example, you can split a file by line and return the list of files after splitting. You can use the built-in split command to split the file. To return the file list name, you can first split the file into self-built subdirectories, and then use the OS. listdir obtains all files, moves these files to the upper-level directory (the new directory specified by the function parameter), deletes the self-built subdirectory, and returns the list of file names.
The Code is as follows:
# Create a new path def make_dirs (path): if not OS. path. isdir (path): OS. makedirs (path) # obtain the number of lines of the file def get_total_lines (file_path): if not OS. path. exists (file_path): return 0 cmd = 'wc-l % s' % file_path return int (OS. popen (cmd ). read (). split () [0]) # function split_file_by_row: split files by row # filepath: split target file # new_filepath: generate new file path # row_cnt: each file can contain up to several lines # suffix_type: New File suffix type, such as two letters or numbers # return: Split file list def split_file_by_row (filepath, new_filepath, row_cnt, suffix_type = '-d'): tmp_dir = "/users/" make_dirs (new_filepath) make_dirs (new_filepath + tmp_dir) total_rows = get_total_lines (filepath) file_cnt = int (math. ceil (total_rows * 1.0/row_cnt) command = "split-l % d-a2 % s" % (row_cnt, suffix_type, filepath, new_filepath + tmp_dir) OS. system (command) filelist = OS. listdir (new_filepath + tmp_dir) command = "mv % s/* % s" % (new_filepath + tmp_dir, new_filepath) OS. system (command) command = "rm-r % s" % (new_filepath + tmp_dir) OS. system (command) return [new_filepath + fn for fn in filelist]