SQL Server administration and T-SQL development, Web Programming with ASP.NET, HTML5 and Javascript, Windows Phone 8 app development, SAP Smartforms and ABAP Programming, Windows 7, Visual Studio and MS Office software
Python Programming and Python Code Tutorials for Programmers


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.

Python code to read text file to list object

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.

import json

filename = "poem.txt"
poem = []

def lambda_handler(event, context):

   poem = readPoemFile(filename)
   print(poem)

   return {
      'statusCode': 200,
      'body': json.dumps(poem, ensure_ascii=False)
   }

def readPoemFile(filename):

   with open(filename, "r") as file:
      for line in file:
         words = line.strip().split()
         poem.extend(words)

   return poem
Sample Python Code to Read from Text File to List Object

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.

output of Python code reading text file contents into list

Above is the output of the Python code execution. Hope this is useful for AWS Lambda developers coding in Python.



Python Tutorials


Copyright © 2004 - 2021 Eralper YILMAZ. All rights reserved.