Python Code Sample to Read Text File and Populate List Object
In this Python tutorial for AWS Lambda developers, I want to show how they can read a text file which is stored locally on the Lambda running machine and stored each line of the text file by splitting it into words as a separate item of an output list object.
I shared the source code below and as seen in the screenshot, the text file is named poem.txt and is stored in the root folder of the AWS Lambda function source codes.
The poem file includes a part of the famous Turkish poet Orhan Veli.
With Open method in Python, it is possible to open the target text file in readonly mode.
Then as seen in the code, with FOR loop, we can loop through each line of the text file. Each line is stored temporarily in a string variable named line and processed by splitting text line into individual words. The outcome list of the split method named words is appended to the poem list with each the iteration in the FOR loop.
Please note that the json.dumps method call is used with ensure_ascii equals to False. This is because the text file contains Turkish characters including non-ascii characters.
Above is the output of the Python code execution. Hope this is useful for AWS Lambda developers coding in Python.