How to set or change line endings of a text file in Python

With a few lines of code and an API, I am about to save you the hours of time that you would have spent trying to set line endings in Python. Let’s dive in.

Our API will, of course, need its client. Let’s install it with pip install, as seen below.

pip install cloudmersive-convert-api-client

Now it’s time for edit_text_change_line_endings, which we call like so:

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.EditTextApi(cloudmersive_convert_api_client.ApiClient(configuration))line_ending_type = 'line_ending_type_example' # str | Required; 'Windows' will use carriage return and line feed, 'Unix' will use newline, and 'Mac' will use carriage returninput_file = '/path/to/file' # file | Input file to perform the operation on.try:# Set, change line endings of a text fileapi_response = api_instance.edit_text_change_line_endings(line_ending_type, input_file)pprint(api_response)except ApiException as e:print("Exception when calling EditTextApi->edit_text_change_line_endings: %s\n" % e)

You can input your text file, as well as your line ending choice: Mac, Windows, or Unix. Now sit back, relax, and a moment later you will have your text file back with the new line endings. How easy was that! This same library also includes a function for determining the line endings of a text file, as well as many other useful things.