How to split a single TXT file using a string delimiter in Python

Today’s topic might seem rather complex and intimidating on first appraisal. If you were to approach it in the usual manner of writing the code yourself, you would be right — it’s very difficult. This API, however, will allow you to quickly and easily use delimiters like commas, pip characters, and slashes to split your text document for easier conversion to database applications like Excel and CSV or use in a programming language.

Image for post
Image for post

This API will first need its client to be installed, so let’s do that with pip install right now.

pip install cloudmersive-convert-api-client

Then we can call our function, SplitDocumentApi:

from __future__ import print_function
import time
import cloudmersive_convert_api_client
from cloudmersive_convert_api_client.rest import ApiException
from pprint import pprint
# Configure API key authorization: Apikey
configuration = cloudmersive_convert_api_client.Configuration()
configuration.api_key['Apikey'] = 'YOUR_API_KEY'
# create an instance of the API class
api_instance = cloudmersive_convert_api_client.SplitDocumentApi(cloudmersive_convert_api_client.ApiClient(configuration))
input_file = '/path/to/inputfile' # file | Input file to perform the operation on.
split_delimiter = 'split_delimiter_example' # str | Required; String to split up the input file on
skip_empty_elements = true # bool | Optional; If true, empty elements will be skipped in the output (optional)
try:
# Split a single Text file (txt) by a string delimiter
api_response = api_instance.split_document_txt_by_string(input_file, split_delimiter, skip_empty_elements=skip_empty_elements)
pprint(api_response)
except ApiException as e:
print("Exception when calling SplitDocumentApi->split_document_txt_by_string: %s\n" % e)

With that, you can easily inform your applications on the preferred order and organization of your text files. To use this API, you can retrieve your free API Key from the Cloudmersive website. This will give you access to 800 monthly calls across our library of APIs.

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