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.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-06-28 01:26:51 +0000
Seen: 23 times
Last updated: Jun 28 '23
How can one generate a list by using a portion of another list?
How can Swagger V3 use Schema Annotation to transform a List of Long to look like a List of String?
How can I modify the width of the column filter in an R shiny datatable?
How can dote be eliminated from the menu items in HTML?
How can an EditForm validate a list object in MudBlazor?
How do you update a dataframe within a for loop in R after passing a list?
How can resetting a list be avoided during a loop?
What is the LINQ query to retrieve the employee with the second highest salary?