How can I parse a text file in Python** and perform the following tasks? I have a text file (.txt) that looks like this:
Date, Day, Sect, 1, 2, 3
1, Sun, 1-1, 123, 345, 678
2, Mon, 2-2, 234, 585, 282
3, Tue, 2-2, 231, 232, 686
Here are my goals:
-
Read the text file by line as a separate element in a list and split each line by commas, while removing unnecessary newline characters (
\n
). -
Set the first row (
Date, Day, Sect, 1, 2, 3
) as the dictionary keys and the subsequent rows as their corresponding values in a dictionary. However, the code I have currently:
file = open('abc.txt', mode='r', encoding='utf-8-sig')
lines = file.readlines()
file.close()
my_dict = {}
my_list = []
for line in lines:
line = line.split(',')
line = [i.strip() for i in line]
Has two issues:
- The first row should also be set as a dictionary.
- When I add the dictionary to the list with
my_list.append(my_dict)
, only the last row is saved, not all the rows.
-
Create a list that includes the dictionary as elements.
-
After creating the list of dictionaries, I want to subset the elements based on specific conditions. For example, I want to select the elements where the
Sect
is2-2
. The expected result would look like this:
[{'Date': '2', 'Day': 'Mon', 'Sect': '2-2', '1': '234', '2': '585', '3': '282'},
{'Date': '3', 'Day': 'Tue', 'Sect': '2-2', '1': '231', '2': '232', '3': '686'}]
Can someone help me achieve this using parse text file Python?