1 | initial version |
You can read the text file line by line and append the first element of each line to a list.
Here's an example code:
my_list = []
with open('file.txt', 'r') as f:
for line in f:
elements = line.strip().split()
my_list.append(elements[0])
In this code, we use the open()
function to open the file named file.txt
. We then iterate over each line in the file using a for
loop. For each line, we first strip any whitespace using the strip()
method, and then split the line into a list of elements using the split()
method. We then append the first element of this list to my_list
.
After the loop completes, my_list
will contain all the first elements from the file.