Converting a text file into a List with Python!

The following code reads all lines of a text file, removes the break-line characters and converts it all into a list.

For this script, i’ll assume that: the text file exists and has some content … (but you should verify this before performing the operations).

with open(filePath, "r") as textFile:
    lines = textFile.readlines()
    lines = list(map(lambda s: s.strip(), lines))
    return lines

Using the “with” statement, it’s not necessary to explicitly close the text file. As soon as the textFile variable goes of scope, the file will be closed automatically.

The following two tabs change content below.
Software Architect and Backend Developer (almost Fullstack), I usually work with C#, PowerShell, Python, Golang, bash and Unity (this one is more for a hobby). I'm always looking for something new to learn, adding new tools to my utility belt.
Posted in Python and tagged , , , , .