How to read a text file into a list or an array with Python
One way to read a text file into a list or an array with Python is to use the split()
method. Here is a code snippet that demonstrates how to do this:
with open('file.txt', 'r') as file:
data = file.read().splitlines()
In the above code snippet, file.txt
is the name of the text file that you want to read, and 'r'
is the mode in which the file is opened ('r'
stands for "read"). The with open
statement is used to open the file, and the as file
part is used to give the file a more convenient name to work with.
The read()
method reads the entire contents of the file, and the splitlines()
method is used to split the contents of the file into a list of strings, one string for each line of the file.
Alternatively, you can also use readlines()
to get the same result, here is the code snippet
with open('file.txt', 'r') as file:
data = file.readlines()
The readlines()
method reads the entire contents of the file, it returns a list where each element is a line in the file.