Search code examples
pythonlistcsvfile-handling

It's showing \n when printing the list


The output:

{'name': 'Peter', 'surname': ' Abdilla', 'DOB': ' 22/02/1986', 'mobileNo': '79811526', 'locality': ' Zabbar\n'}
{'name': 'John', 'surname': ' Borg', 'DOB': ' 12/04/1982', 'mobileNo': '99887654', 'locality': ' Paola\n'}

The expected output is supposed to be:

{'name': 'Peter', 'surname': ' Abdilla', 'DOB': ' 22/02/1986', 'mobileNo': '79811526', 'locality': ' Zabbar'}
{'name': 'John', 'surname': ' Borg', 'DOB': ' 12/04/1982', 'mobileNo': '99887654', 'locality': ' Paola'}

Solution

  • Each line in CSV has an endLine character which is '\n', so when you try to read the contents of the csv file line by line, '\n' will also be in the string.

    So, we just need to replace the '\n' with an empty string.

    To fix this, use the python's string replace() function.

    while True:
        x = file.readline()
        x = x.replace('\n', '')
        if x == '':
            break
        else:
            value = x.split(',')
            contact = dict(tuple(zip(keys,value)))
            filename.append(contact)