This is the fastest way to get data from an external txt file that is in the same dir of the .py file with this code.
You simply assign a name to a list that will get the data opening the txt file and splitting the data by the method split(), assuming that each element of the list will be a line of the text.
The text (data.txt) will contain this data
data 1
data 2
data 3
data 4
data 5
The code in the py file (data.py) will read those data with this code:
>>> with open('data.txt',encoding='UTF-8') as data:
>>> data = data.readlines()
...
>>> print(data)
['data 1','data 2','data 3','data 4','data 5']
so, the read() method get the content of the txt file as a strint and the split() methods returns a list from the string in which each element is a line, because of the argument passed '\n' that indicates a new line. In fact, read() returns a string that has '\n' at the end of each line. With split('\n') the string is divided and so each line becomes an element of the list.
This comment has been removed by the author.
ReplyDelete