Suppose I have a text file that has the following in it:
A,B:C,D
I know that if I didn't have the colon and just had A,B, I could do
infile = open(filename, "r")
readfile = infile.readlines()
AB = readfile[0]
for x in AB:
stripab = AB.strip()
A, B = AB.split(",")
# Want to add the two to a list after
mydict[A] = B
How would I be able to split C,D and store them into the same variables as A,B in order to add them to the dictionary?
CodePudding user response:
You can do the same thing as in your example, but twice:
infile = open(filename, "r")
readfile = infile.readlines()
AB = readfile[0]
stripab = AB.strip()
firstSplit = stripab.split(":")
A, B = firstSplit[0].split(",")
C, D = firstSplit[1].split(",")
mydict[A] = B
mydict[C] = D
CodePudding user response:
If "A,B:C,D" is just the first line in your opened file, then you don't need to run a for loop. Simple if-else logic below should work.
infile = open(filename, "r")
readfile = infile.readlines()
AB = readfile[0]
lst = AB.strip().split(':')
if len(lst) == 2:
A, B = lst[0].split(',')
mydict[A] = B
C, D = lst[1].split(',')
mydict[C] = D
elif len(lst) == 1:
A, B = lst[0].split(',')
mydict[A] = B