Using python to split text files by line,

Source: Internet
Author: User

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]

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.