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 cloudmersive_convert_api_client.rest 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.

Image for post
Image for post

Written by

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store