I'm trying to read this text file line by line and store specific information from the line to use it after in my program. There are 5 pieces of information and 4 of them are separated with "_". The last one is separated with ":".
Txt file sample:
Shahran_1_True_True:61666.67
Shahran_1_True_True:61666.67
Pardis_2_True_True:18333.33
Shahrake Qods_2_True_True:30083.33
Shahrake Gharb_2_True_True:233333.33
For example, I need to store Shahran, Pardis and Shahrake Qods in a list. I can read the lines but I can't separate the information. Can anyone show me a way of doing this?
CodePudding user response:
Have you tried this?
my_list = []
with open('my_text.txt') as f:
lines = f.readlines()
for line in lines:
my_list.append(line.split('_')[0]) #index [0] to get the first element
my_list = list(set(my_list)) #get only unique names
print(my_list)
Output
['Shahran', 'Shahrake Gharb', 'Shahrake Qods', 'Pardis']
CodePudding user response:
You've got to split each line at _
and :
. You probably want to store all the information as a list
of dict
s.
Be sure to read the documentation on the str.split
method.
records = []
with open('C:\Stuff\SOshittemp.txt') as f:
for line in f:
column1, column2, column3, remaining = line.split("_")
column4, column5 = remaining.split(":")
record = {}
record["column1"] = column1
record["column2"] = column2
record["column3"] = column3
record["column4"] = column4
record["column5"] = column5
records.append(record)
records
is now a list made up of 6 dict
s. To get to the strings stored within, you can access them like so:
print(records[0]["column1"])
Output:
Shahran