Anthony Anthony - 1 month ago 6x
Python Question

Loading text data in Python

if I am given a text data which contains a list of numbers without specifying which number refers to which variable, unlike the excel format, how does one load these number as data using Python?

Sorry for the amateur question, but I am just introduced to python.


Hi Anthony,

Parsing your file depends on the format it is using. Assuming your file is a sequence of numbers separated by a new line, here's how I would proceed:

First of all, you have to open your file. To do so, you could use the standard open function.

open takes as a first argument the path of the file you want to work with, and a second argument being the mode, which could be 'r' to read, 'w' to overwrite, and 'a' to append text to the file as well as the binary variants (default is 'r'). Not talking about open's other parameters.

number_file = open('numbers.txt')  # implicitly read mode

numbers = []  # the list in which we're going to store all our numbers

# iterates over each line of the file
for line in number_file:
    n = int(line)      # parsing the string into an integer  
    numbers.append(n)  # adding the number to your list


The cool thing is, open is also what we call in Python a context manager. Behind this jargon lies a really simple concept which is doing action before and after a given code.

The with keyword allows you to use a context manager:

with open('numbers.txt') as number_file:
    for line in number_file:
        n = int(line) 

If you didn't notice, you don't have to close your file using context managers, because open is taking care of that.

That's why it is recommended rather than the previous method: You can't forget to close your file, thus it's less likely to have an OS error if you open the file twice (e.g. if you want to modify and save a serialized object).