How to split a single Text File TXT into Lines in Python
Splitting text files into lines is one of those features that you don’t really notice until you don’t have it. This task can be deceptively difficult, considering its mundane nature. Thankfully, we have a correspondingly simple way to get it into your project: an API. We begin by installing that API’s client with this pip install command.
pip install cloudmersive-convert-api-client
Now we call the function we need, which goes by split_document_txt_by_line.
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)
Done! Any text file that you throw into this code as an input will now be split into a set of lines. Talk about easy!