Thie is an example of my text file:
A, 100 101 102
B, 103 104
I want to read from this file and create a dictionary.
Here is my code:
def readFromFile():
d = {} # empty dictionary
with open('file.txt') as fr: #read from text file
for line in fr.readlines(): # reading text file by line
k, v = line.split(',') # splitting the line on text file by ',' to define the key and values
v = v.split() # splitting the values in each key into a list
for n in range( len(v) ):
v[n] = int(v[n]) # convert student id in list from str to int
d[k] = v # build dictionary with keys and its values
return d
here is how my output looks like:
{'A': [100, 101, 102], 'B': [103, 104]}
I want to update the values of A with int 209 using this function:
def writeToFile(d):
with open('file.txt', 'w') as fw:
for k,v in d.items():
print(f'{k}, {v}', file = fw)
My file will be written as this:
A, [100, 101, 102, 209]
This cause the function readFromFile() to throw errors as the text file is no longer in the same format.
Desired output on text file is this:
A, 100 101 102 209