0

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
  • I don't think that is possible with dict. – Challe Aug 27 '20 at 16:12
  • You can't. That's invalid syntax and it's just a symptom of an XY problem elsewhere – roganjosh Aug 27 '20 at 16:12
  • You're focusing on the wrong thing. There is nothing wrong with the current output. What you're doing with it is likely to be the issue for you – roganjosh Aug 27 '20 at 16:13
  • maybe you could do this `{'A': '100, 101, 102', 'B':' 103, 104'}` but not this `{'A': 100, 101, 102, 'B': 103, 104}` – badhusha muhammed Aug 27 '20 at 16:14
  • Thank you. My real problem is when I try to write on the original file when I update the dictionary. For e.g, I update values of A with int 209. I would like to be able to write on the text file as `A, 100 101 102 209`. at this point, it will always be written as: `A, [100, 101, 102, 209]` – Mardhiah Hamid Aug 27 '20 at 22:18

1 Answers1

0

The problem is that you are not writing the file in the expected format. You'll need to write the same format that you read.

def write_to_file(filename, d):
    with open(filename, 'w') as fw:
        for k,v in d.items():
            line_data = ' '.join(map(str, v))
            print('{}, {}'.format(k, line_data), file = fw)

Your readFromFile function does not validate the format. So of course it throws errors -- just catch any error and report that as bad file contents.

To expand on the line_data, you want to combine a list into a single string, separated by spaces, thus you will use space as the separator, and the list as the iterable in a call to https://docs.python.org/3/library/stdtypes.html#str.join

But of course, you can't use str.join to join ints. You need to convert all of them to str, so you pass it map(str, v) as the iterable to join. The built-in function https://docs.python.org/3/library/functions.html#map just applies a function (in this case convert to str) to each item.

Kenny Ostrom
  • 5,639
  • 2
  • 21
  • 30