How to split a single Text File TXT into Lines in Python

Splitting TXT files up into lines can be incredibly useful, as you well know. You are probably starting to also realize that performing this seemingly easy task is actually a bit more tricky. Today’s post is here to de-mystify that process for you.

Pip install the Cloudmersive API client first.

pip install cloudmersive-convert-api-client

To proceed, use a key to instantiate an API. Now, call split_document_txt_by_line from said API instance, providing the file path.

from __future__ import print_functionimport timeimport cloudmersive_convert_api_clientfrom import ApiExceptionfrom pprint import pprint# Configure API key authorization: Apikeyconfiguration = cloudmersive_convert_api_client.Configuration()configuration.api_key['Apikey'] = 'YOUR_API_KEY'# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed# configuration.api_key_prefix['Apikey'] = 'Bearer'# create an instance of the API classapi_instance = cloudmersive_convert_api_client.SplitDocumentApi(cloudmersive_convert_api_client.ApiClient(configuration))input_file = '/path/to/file' # file | Input file to perform the operation on.try:# Split a single Text file (txt) into linesapi_response = api_instance.split_document_txt_by_line(input_file)pprint(api_response)except ApiException as e:print("Exception when calling SplitDocumentApi->split_document_txt_by_line: %s\n" % e)

Any TXT file that you submit will be split up into lines and returned to you. And just like that, our work here is done.